4

同じ数の行を含む 2 つのファイルがあります。

"file1.txt" contains following lines:

 Attitude is a little thing that makes a big difference
 The only disability in life is a bad attitude
 Abundance is, in large part, an attitude
 Smile when it hurts most

"file2.txt" contains:

 Attitude is a little thing that makes a big difference
 Everyone has his burden. What counts is how you carry it
 Abundance is, in large part, an attitude
 A positive attitude may not solve all your problems  

2つのファイルを1行ずつ比較したいのですが、2つのファイル間で行の不一致があれば、

 print "mismatch in line no: 2"
 print "mismatch in line no: 4"   #in this case lineno: 2 and lineno: 4 varies from second file

試してみましたが、file2 の行とは異なる file1 の行しか印刷できません。一致しない行の行番号を印刷できませんか??

 My code:
 with open("file1.txt") as f1:
    lineset = set(f1)
 with open("file2.txt") as f2:
    lineset.difference_update(f2)
    for line in lineset:
        print line
4

4 に答える 4

8

itertools.izipと の使用enumerate:

import itertools

with open('file1.txt') as f1, open('file2.txt') as f2:
    for lineno, (line1, line2) in enumerate(itertools.izip(f1, f2), 1):
        if line1 != line2:
            print 'mismatch in line no:', lineno
于 2013-12-19T16:27:45.693 に答える
1

difflibモジュールを使用できる場合があります。difflib.Differそのクラスを使用した簡単な例を次に示します。

import difflib
import sys

with open('file1.txt') as file1, open('file2.txt') as file2:
    line_formatter = '{:3d}  {}'.format
    file1_lines = [line_formatter(i, line) for i, line in enumerate(file1, 1)]
    file2_lines = [line_formatter(i, line) for i, line in enumerate(file2, 1)]
    results = difflib.Differ().compare(file1_lines, file2_lines)
    sys.stdout.writelines(results)

出力:

    1  Attitude is a little thing that makes a big difference
-   2  The only disability in life is a bad attitude
+   2  Everyone has his burden. What counts is how you carry it
    3  Abundance is, in large part, an attitude
-   4  Smile when it hurts most
+   4  A positive attitude may not solve all your problems

diff最初の列のマイナス文字とプラス文字は、典型的なユーティリティ プログラム スタイルで置き換えられた行を示します。インジケータがないということは、行が両方のファイルで同じであることを意味します。必要に応じてそれらの出力を抑制できますが、例を単純にするために、compare()メソッドが作成するすべてが出力されます。

参考までに、2 つのファイルの内容と行番号を並べて示します。

1  Attitude is a little thing that makes a big difference    Attitude is a little thing that makes a big difference
2  The only disability in life is a bad attitude             Everyone has his burden. What counts is how you carry it
3  Abundance is, in large part, an attitude                  Abundance is, in large part, an attitude
4  Smile when it hurts most                                  A positive attitude may not solve all your problems
于 2013-12-19T17:37:49.820 に答える