【发布时间】:2015-09-20 20:04:33
【问题描述】:
我有一个输入文件 word.txt。我正在尝试在 python 中将文件随机拆分为 75%-25%。
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'
traingdata = len(lines)* 75 // 100
testdata = len(lines)-traingdata
with open(outfilename1, 'w') as f:
f.writelines(lines[:traingdata])
with open(outfilename2, 'w') as f:
f.writelines(lines[:testdata])
但是这段代码在第一个输出文件中写入原始文件的前 75%,在第二个输出文件中再次写入原始文件的 25%。您能否建议我一些解决方法。
【问题讨论】: