【发布时间】:2017-11-07 22:46:32
【问题描述】:
我有一个包含几百万行文本的大文件。我想随机地从这个文件中提取一个较小的(250000 行)。我做了以下代码,但它非常慢,实际上慢得无法使用。我该怎么做才能加快速度?
def get_shorter_subset(fname, new_len):
"""Extract a random shorter subset of length new_len from a given file"""
out_lines = []
with open(fname + "short.out", 'w') as out_file:
with open(fname, 'r') as in_file:
all_lines = in_file.readlines()
total = len(all_lines)
print "Total lines:", total
for i in range(new_len):
line = np.random.choice(all_lines)
out_lines.append(line.rstrip('\t\r\n'))
#out_file.write(line.rstrip('\t\r\n'))
print "Done with", i, "lines"
all_lines.remove(line)
out_file.write("\n".join(out_lines))
【问题讨论】: