python - 如何将多个文件中的行号提取到单个文件

标签 python

我正在开发一个统计机器翻译项目,其中一个文件夹 (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/

相关文章:

python - 如何使用 dask 高效地并行化时间序列预测?

python - pathlib.Path 的子类对象在 pickle.load 后丢失自定义属性

python - 在 matplotlib 中将 x 和 y 数据作为关键字参数传递?

python - 黄色车道线的 HSL 范围

python - 想要了解 Spark Streaming 的工作原理吗?

python - 无法使用 "ERROR: Failed building wheel for pyaudio"在Google Colab上安装pyaudio

python - 如何在 pyximport.install() 之后导入 h5py

python - 仅提取属于特定 kmeans 标签的样本

python - 如何将此代码从 matlab 转换为 python?

python - 如何更新 django-haystack 的单个记录?