我有两种不同语言的两个文本文件,它们被排成一行行。即在textfile1的第一行对应于textfile2第一行,依此类推等等。
有没有一种方法来读取两种文件一行一行地同时?
下面的文件应该怎么样子,想象每个文件的行数约为1,000,000样本。
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:
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,通过逐行地读取。因此,如何将它做?
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
。
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
Python不让你逐行读取,并且它甚至默认的行为 - 你只是遍历文件等不会遍历列表。
在同时做两项iterables 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())
我们可以使用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
如果它很重要。