python:将文件拆分为两个文件的最快方法是什么,每个文件的行数是原始文件的一半,这样两个文件中的每一个中的行都是随机的?
例如:如果文件是 1 2 3 4 5 6 7 8 9 10
它可以分为:
3 2 10 9 1
4 6 8 5 7
这种操作通常称为“分区”。虽然没有内置的分区函数,但我找到了这篇文章:Python 中的分区。
鉴于该定义,您可以这样做:
import random
def partition(l, pred):
yes, no = [], []
for e in l:
if pred(e):
yes.append(e)
else:
no.append(e)
return yes, no
lines = open("file.txt").readlines()
lines1, lines2 = partition(lines, lambda x: random.random() < 0.5)
Run Code Online (Sandbox Code Playgroud)
请注意,这并不一定完全相同的文件一分为二,但它会在平均水平。
您可以只加载文件,调用random.shuffle结果列表,然后将其拆分为两个文件(未经测试的代码):
def shuffle_split(infilename, outfilename1, outfilename2):
from random import shuffle
with open(infilename, 'r') as f:
lines = f.readlines()
# append a newline in case the last line didn't end with one
lines[-1] = lines[-1].rstrip('\n') + '\n'
shuffle(lines)
with open(outfilename1, 'w') as f:
f.writelines(lines[:len(lines) // 2])
with open(outfilename2, 'w') as f:
f.writelines(lines[len(lines) // 2:])
Run Code Online (Sandbox Code Playgroud)
random.shufflelines就地洗牌,几乎可以完成所有工作。Python 的序列索引系统(例如lines[len(lines) // 2:])使事情变得非常方便。
我假设该文件不是很大,即它可以轻松地放入内存中。如果不是这种情况,您需要做一些更花哨的事情,可能使用该linecache模块从您的输入文件中读取随机行号。我想您可能想要生成两个行号列表,使用与上面显示的技术类似的技术。
更新:启用时更改/为//逃避问题__future__.division。
| 归档时间: |
|
| 查看次数: |
3121 次 |
| 最近记录: |