[英]Reading two text files line by line simultaneously
我有兩個使用兩種不同語言的文本文件,它們逐行對齊。 即 textfile1 中的第一行對應於 textfile2 中的第一行,依此類推。
有沒有辦法同時逐行讀取兩個文件?
下面是文件應該是什么樣子的示例,假設每個文件的行數大約為 1,000,000。
文本文件 1:
This is a the first line in English
This is a the 2nd line in English
This is a the third line in English
文本文件 2:
C'est la première ligne en Français
C'est la deuxième ligne en Français
C'est la troisième ligne en Français
期望的輸出
This is a the first line in English\tC'est la première ligne en Français
This is a the 2nd line in English\tC'est la deuxième ligne en Français
This is a the third line in English\tC'est la troisième ligne en Français
Read two textfile line by line simultaneously -java有一個 Java 版本,但是 Python 不使用逐行讀取的 bufferedreader。 那么怎么做呢?
with open("textfile1") as textfile1, open("textfile2") as textfile2:
for x, y in izip(textfile1, textfile2):
x = x.strip()
y = y.strip()
print(f"{x}\t{y}")
在 Python 2 中,將內置zip
替換為itertools.izip
:
from itertools import izip
with open("textfile1") as textfile1, open("textfile2") as textfile2:
for x, y in izip(textfile1, textfile2):
x = x.strip()
y = y.strip()
print("{0}\t{1}".format(x, y))
with open(file1) as f1, open(fil2) as f2:
for x, y in zip(f1, f2):
print("{0}\t{1}".format(x.strip(), y.strip()))
輸出:
This is a the first line in English C'est la première ligne en Français
This is a the 2nd line in English C'est la deuxième ligne en Français
This is a the third line in English C'est la troisième ligne en Français
我們可以使用generator
來更方便地打開文件,它可以輕松地支持同時對更多文件進行迭代。
filenames = ['textfile1', 'textfile2']
def gen_line(filename):
with open(filename) as f:
for line in f:
yield line.strip()
gens = [gen_line(n) for n in filenames]
for file1_line, file2_line in zip(*gens):
print("\t".join([file1_line, file2_line]))
筆記:
python 3
代碼。 對於python 2
,像其他人說的那樣使用itertools.izip
。zip
將在迭代最短文件后停止,如果重要,請使用itertools.zip_longest
。Python 確實允許您逐行閱讀,這甚至是默認行為 - 您只需像遍歷列表一樣遍歷文件。
wrt/一次迭代兩個可迭代對象,itertools.izip 是你的朋友:
from itertools import izip
fileA = open("/path/to/file1")
fileB = open("/path/to/file2")
for lineA, lineB in izip(fileA, fileB):
print "%s\t%s" % (lineA.rstrip(), lineB.rstrip())
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.