我需要在python中获取大文件(数十万行)的行数.记忆和时间方面最有效的方法是什么?
目前我这样做:
def file_len(fname):
with open(fname) as f:
for i, l in enumerate(f):
pass
return i + 1
Run Code Online (Sandbox Code Playgroud)
有可能做得更好吗?
我试过用random.randint(0, 100),但有些数字是一样的.是否有方法/模块来创建列表唯一的随机数?
def getScores():
# open files to read and write
f1 = open("page.txt", "r");
p1 = open("pgRes.txt", "a");
gScores = [];
bScores = [];
yScores = [];
# run 50 tests of 40 random queries to implement "bootstrapping" method
for i in range(50):
# get 40 random queries from the 50
lines = random.sample(f1.readlines(), 40);
Run Code Online (Sandbox Code Playgroud) 如何在SQL中使用高效的简单随机样本?有问题的数据库正在运行MySQL; 我的表至少有200,000行,我想要一个大约10,000的简单随机样本.
"明显"的答案是:
SELECT * FROM table ORDER BY RAND() LIMIT 10000
Run Code Online (Sandbox Code Playgroud)
对于大型表来说,这太慢了:它为每一行调用RAND()(已经将它放在O(n)处)并对它们进行排序,最多使它成为O(n lg n).有没有办法比O(n)更快地做到这一点?
注意:正如Andrew Mao在评论中指出的那样,如果您在SQL Server上使用此方法,则应使用T-SQL函数NEWID(),因为RAND()可能会为所有行返回相同的值.
编辑:5年后
我用更大的表再次遇到了这个问题,并最终使用了@ ignorant的解决方案,并进行了两次调整:
要获取表的1000项样本,我计算行并使用frozen_rand列将结果平均下降到10,000行:
SELECT COUNT(*) FROM table; -- Use this to determine rand_low and rand_high
SELECT *
FROM table
WHERE frozen_rand BETWEEN %(rand_low)s AND %(rand_high)s
ORDER BY RAND() LIMIT 1000
Run Code Online (Sandbox Code Playgroud)
(我的实际实现涉及更多的工作,以确保我没有欠采样,并手动包裹rand_high,但基本的想法是"随机削减你的N到几千.")
虽然这会做出一些牺牲,但它允许我使用索引扫描对数据库进行采样,直到它再次小到ORDER BY RAND()为止.
你知道是否有办法让python random.sample与生成器对象一起工作.我试图从一个非常大的文本语料库中获取随机样本.问题是random.sample()引发以下错误.
TypeError: object of type 'generator' has no len()
Run Code Online (Sandbox Code Playgroud)
我在想,也许有一些方法itertools可以用来自某些东西来做这件事但却找不到任何有点搜索的东西.
一个有点组成的例子:
import random
def list_item(ls):
for item in ls:
yield item
random.sample( list_item(range(100)), 20 )
Run Code Online (Sandbox Code Playgroud)
UPDATE
按照MartinPieters的要求,我做了目前提出了三种方法的一些具体时机.结果如下.
Sampling 1000 from 10000
Using iterSample 0.0163 s
Using sample_from_iterable 0.0098 s
Using iter_sample_fast 0.0148 s
Sampling 10000 from 100000
Using iterSample 0.1786 s
Using sample_from_iterable 0.1320 s
Using iter_sample_fast 0.1576 s
Sampling 100000 from 1000000
Using iterSample 3.2740 s
Using sample_from_iterable 1.9860 s
Using …Run Code Online (Sandbox Code Playgroud) 我需要使用python从大型txt文件中获取N行.这些文件基本上是制表符分隔的表.我的任务有以下限制:
目前我已经编写了以下代码:
inputSize=os.path.getsize(options.input)
usedPositions=[] #Start positions of the lines already in output
with open(options.input) as input:
with open(options.output, 'w') as output:
#Handling of header lines
for i in range(int(options.header)):
output.write(input.readline())
usedPositions.append(input.tell())
# Find and write all random lines, except last
for j in range(int(args[0])):
input.seek(random.randrange(inputSize)) # Seek to random position in file (probably middle of line)
input.readline() # Read the line (probably incomplete). Next input.readline() results in a complete line.
while input.tell() …Run Code Online (Sandbox Code Playgroud) python ×4
random ×4
generator ×1
large-files ×1
line ×1
line-count ×1
mysql ×1
postgresql ×1
readline ×1
sql ×1
text-files ×1