以下是一个示例代码,用于比较多个目标文档和多个源文档。
import difflib
def compare_documents(target_documents, source_documents):
for target_doc in target_documents:
for source_doc in source_documents:
with open(target_doc, 'r') as target_file, open(source_doc, 'r') as source_file:
target_text = target_file.readlines()
source_text = source_file.readlines()
diff = difflib.unified_diff(target_text, source_text, lineterm='')
changes = list(diff)
if len(changes) > 0:
print(f"Differences found between {target_doc} and {source_doc}:")
print('\n'.join(changes))
else:
print(f"No differences found between {target_doc} and {source_doc}")
# Example usage
target_files = ['target_doc1.txt', 'target_doc2.txt']
source_files = ['source_doc1.txt', 'source_doc2.txt']
compare_documents(target_files, source_files)
这个示例代码使用了Python的difflib模块,它提供了多种文本比较算法。在这个例子中,我们使用了unified_diff方法来比较目标文档和源文档的差异,并将差异输出到控制台。
在比较之前,代码会逐个打开目标文档和源文档,并读取它们的内容。然后,使用unified_diff方法比较两个文档的内容,并将差异保存在changes列表中。
最后,代码会检查changes列表的长度,如果大于0,则表示有差异存在,将差异输出到控制台。如果changes列表的长度为0,则表示没有差异存在。
你可以根据自己的需求,修改代码中的文件名和路径,以适应你的具体情况。
上一篇:比较多个列获取最大值并返回特定值