同时逐行读取两个文本文件 [英] Reading two text files line by line simultaneously
问题描述
我有两个使用两种不同语言的文本文件,它们逐行对齐. IE. textfile1中的第一行与textfile2中的第一行相对应,依此类推.
I have two text files in two different languages and they are aligned line by line. I.e. the first line in textfile1 corresponds to the first line in textfile2, and so on and so forth.
是否可以同时逐行读取两个文件?
Is there a way to read both file line-by-line simultaneously?
以下是文件外观的示例,假设每个文件的行数约为1,000,000.
Below is a sample of how the files should look like, imagine the number of lines per file is around 1,000,000.
textfile1:
textfile1:
This is a the first line in English
This is a the 2nd line in English
This is a the third line in English
textfile2:
textfile2:
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
此的Java版本逐行读取两个文本文件同时-java ,但是Python不使用逐行读取的bufferedreader.那怎么办呢?
There is a Java version of this Read two textfile line by line simultaneously -java, but Python doesn't use bufferedreader that reads line by line. So how would it be done?
推荐答案
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))
在Python 3中,将itertools.izip
替换为内置的zip
.
In Python 3, replace itertools.izip
with the built-in zip
.
这篇关于同时逐行读取两个文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!