作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在开发一个统计机器翻译项目,其中一个文件夹 (linenumberfiles/) 中有 15 个文件。每个文件包含多个行号,格式如下(每行一个行号):
12
15
19
我想从 15 个文件中的每个文件中提取 10 个随机行号到单个输出文件 (OutputLinesFile) 棘手的部分是一些文件可能包含少于 10 个行号,在这种情况下我会喜欢将尽可能多的行号提取到输出文件中。输出文件的格式应与输入文件相同(每行一个行号)。这是我到目前为止的代码:
import glob
OutputLinesFile = open('OutputLineNumbers', 'w')
inputfiles=glob.glob('linenumberfiles/*')
for file in inputfiles:
readfile=open(file).readlines()
OutputLinesFile.write( str(readfile) )
OutputLinesFile.close()
有人知道如何解决这个问题吗?预先感谢您的帮助!
最佳答案
您可以在此处使用random.shuffle
和列表切片:
import glob
import random
count = 10 #fetch at least this number of lines
with open('OutputLineNumbers', 'w') as fout:
inputfiles=glob.glob('linenumberfiles/*')
for file in inputfiles:
with open(file) as f:
lines = f.readlines()
random.shuffle(lines) #shuffle the lines
fout.writelines(lines[:count]) #pick at most first 10 lines
或使用random.randrange
:
lines = f.readlines()
lines = [ lines[random.randrange(0, len(lines)] for _ in xrange(count) ]
然后:fout.writelines(lines)
关于python - 如何将多个文件中的行号提取到单个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17166274/
我是一名优秀的程序员,十分优秀!