64

2 つの異なる言語の 2 つのテキスト ファイルがあり、行ごとに並べられています。つまり、textfile1 の最初の行は textfile2 の最初の行に対応し、以下同様です。

両方のファイルを 1 行ずつ同時に読み取る方法はありますか?

以下は、ファイルがどのように見えるかのサンプルです。ファイルあたりの行数が約 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同時に -javaの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 に答える
3

Python では 1 行ずつ読み取ることができます。これはデフォルトの動作でもあります。リストを反復処理するように、ファイルを反復処理するだけです。

wrt/ 一度に 2 つの iterable を反復する場合、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 に答える