簡體   English   中英

如何將行號從多個文件提取到單個文件

[英]How to extract line numbers from multiple files to a single file

我正在做一個統計機器翻譯項目,其中一個文件夾(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)

首先,您應該使用with語句。 在這里閱讀為什么 例:

try:
    with open(file, 'r') as f:
        cont = f.readlines()
except IOError, err:
    print err  

然后,您應該看看random模塊。 要從f中選擇隨機項,請使用sample -方法。 要檢查輸入文件中有多少行,只需使用BIF len()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM