テキストファイルを比較する
先日いっていた、ふたつのテキストファイルの一致性を比較するPythonスクリプトを掲載します。目前の目的をやっつけるのが最優先だったので、どんなファイルにも有効だとは思わないし、ふたつのテキストファイルの行数が一致した場合の処理を書いてなかったりもしますが(つまり、評価する対象は最後まで行数が一緒にならなかったってことです)、まあ参考になれば幸いです。
いや、参考になるかなあ……。
veri.py
# -*- coding: utf-8 -*- import sys import os.path import codecs import re argvs = sys.argv file_a = argvs[1] file_b = argvs[2] def check_text(file_a, file_b): if not os.path.exists(file_a): raise IOError('File %s not exists.' % file_a) if not os.path.exists(file_b): raise IOError('File %s not exists.' % file_b) with codecs.open(file_a, 'r', 'shift-jis') as fa: with codecs.open(file_b, 'r', 'shift-jis') as fb: texta = fa.readlines() textb = fb.readlines() if len(texta) == len(textb): print(texta) else: print('Number of lines is different.') print('File %s has %s lines, file %s has %s lines.' % \ (file_a, len(texta), file_b, len(textb))) texta = ' '.join(texta) textb = ' '.join(textb) sps = re.compile('\s+') texta = sps.sub(' ', texta) textb = sps.sub(' ', textb) texta = texta.upper() textb = textb.upper() lena = len(texta) lenb = len(textb) if lena == lenb: print(lena) for i in range(lena): if texta[i] != textb[i]: print('%s: %s %s' % (i, texta[i:i + 3], textb[i:i + 3])) exit() else: print('Length of text is not match.') print('File %s has %s chars, file %s has %s chars.' %\ (file_a, lena, file_b, lenb)) if lena < lenb: leno = lena else: leno = lenb for i in range(leno): if texta[i] != textb[i]: print('%s: %s %s' % (i, texta[i:i + 3], textb[i:i + 3])) exit() check_text(file_a, file_b)