この例では2つのテキストを比較します。初めに、改行文字で終了する独立した 1行の連続した(ファイル形式オブジェクトのreadlines()メソッドに よって得られるような)テキストを用意します。
>>> text1 = ''' 1. Beautiful is better than ugly. ... 2. Explicit is better than implicit. ... 3. Simple is better than complex. ... 4. Complex is better than complicated. ... '''.splitlines(1) >>> len(text1) 4 >>> text1[0][-1] '\n' >>> text2 = ''' 1. Beautiful is better than ugly. ... 3. Simple is better than complex. ... 4. Complicated is better than complex. ... 5. Flat is better than nested. ... '''.splitlines(1)
次にDifferオブジェクトをインスタンス化します。
>>> d = Differ()
注意:Differオブジェクトをインスタンス化するとき、 ``junk.''である列と文字をフィルタリングす関数を渡すことができます。 詳細はDiffer()コンストラクタを参照してください。
最後に、2つを比較します。
>>> result = list(d.compare(text1, text2))
resultは文字列のリストなので、pretty-printしてみましょう。
>>> from pprint import pprint >>> pprint(result) [' 1. Beautiful is better than ugly.\n', '- 2. Explicit is better than implicit.\n', '- 3. Simple is better than complex.\n', '+ 3. Simple is better than complex.\n', '? ++ \n', '- 4. Complex is better than complicated.\n', '? ^ ---- ^ \n', '+ 4. Complicated is better than complex.\n', '? ++++ ^ ^ \n', '+ 5. Flat is better than nested.\n']
これは、複数行の文字列として、次のように出力されます。
>>> import sys
>>> sys.stdout.writelines(result)
1. Beautiful is better than ugly.
- 2. Explicit is better than implicit.
- 3. Simple is better than complex.
+ 3. Simple is better than complex.
? ++
- 4. Complex is better than complicated.
? ^ ---- ^
+ 4. Complicated is better than complex.
? ++++ ^ ^
+ 5. Flat is better than nested.