64

我有两种不同语言的两个文本文件,它们逐行对齐。即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

有一个 Java 版本的Read two textfile 同时行 -java,但 Python 不使用逐行读取的 bufferedreader。那么它会怎么做呢?

4

4 回答 4

109
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.

于 2012-07-02T14:00:17.850 回答
23
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
于 2012-07-02T14:00:02.497 回答
4

我们可以使用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]))

笔记:

  1. 这是python 3代码。For python 2,itertools.izip像其他人说的那样使用。
  2. zip在最短的文件被迭代后将停止,itertools.zip_longest如果重要,请使用。
于 2019-05-23T04:11:18.837 回答
3

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())
于 2012-07-02T14:03:32.487 回答