difflib是python提供的比较序列(string list)差异的模块。实现了三个类:
1>SequenceMatcher 任意类型序列的比较 (可以比较字符串)
2>Differ 对字符串进行比较
3>HtmlDiff 将比较结果输出为html格式.
建议你使用SequenceMatcher比较器,给你个例子吧。
SequenceMatcher实例:
import difflibfrom pprint import pprint
a = 'pythonclub.org is wonderful'
b = 'Pythonclub.org also wonderful'
s = difflib.SequenceMatcher(None, a, b)
print "s.get_matching_blocks():"
pprint(s.get_matching_blocks())
print "s.get_opcodes():"
for tag, i1, i2, j1, j2 in s.get_opcodes():
print ("%7s a[%d:%d] (%s) b[%d:%d] (%s)" % (tag, i1, i2, a[i1:i2], j1, j2, b[j1:j2]))
输出为:
s.get_matching_blocks():
[(1, 1, 14), (16, 17, 1), (17, 19, 10), (27, 29, 0)]
s.get_opcodes():
replace a[0:1] (p) b[0:1] (P)
equal a[1:15] (ythonclub.org ) b[1:15] (ythonclub.org )
replace a[15:16] (i) b[15:17] (al)
equal a[16:17] (s) b[17:18] (s)
insert a[17:17] () b[18:19] (o)
equal a[17:27] ( wonderful) b[19:29] ( wonderful)
SequeceMatcher(None,a,b)创建序列比较对象,将以a作为参考标准进行
Sequecematcher(None,b,a)创建序列比较对象,将以b作为参考标准进行
a,b表示待比较的两个序列,生成序列比较对象后,调用该对象的get_opcodes()方法,将返回一个元组(tag,i1,i2,j1,j2).tag表示序列分片的比较结果.i1,i2表示序列a的索引,j1,j2表示序列b的索引.
get_opcodes()返回元组(tag,i1,i2,j1,j2)的含义
这里假设题目里面提到的”单独两个JSON文件的比较方法“的函数是compare_two_files,它接受两个文件的文件名作为参数。
from pathlib import Path
def compare_two_folders(from_folder, to_folder):
from_folder = Path(from_folder)
to_folder = Path(to_folder)
for json_file in from_folder.glob('*.json'):
json_file_name = json_file.name
json_file_to_compare = to_folder / f'a{json_file_name}'
compare_tow_files(json_file, json_file_to_compare)