私は数百万行の大きなファイルを持っています。私はランダムに一様にこのファイルからより小さな(250000行)を抽出したいと思います。私は次のコードを実行しましたが、それは驚くほど非常に遅く、実際には使えないほど遅いです。私はそれをスピードアップするために何ができますか?Pythonで大きなファイルのサブセットを効率的に抽出
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))