以下是一个使用Python比较两个文本文件中字符串的示例代码:
def compare_text_files(file1, file2):
with open(file1, 'r') as f1, open(file2, 'r') as f2:
# 读取文件内容并将字符串拆分为列表
text1 = f1.read().split()
text2 = f2.read().split()
# 比较两个列表中的字符串
common_strings = set(text1) & set(text2)
unique_strings_file1 = set(text1) - set(text2)
unique_strings_file2 = set(text2) - set(text1)
# 打印结果
print(f"共同的字符串: {common_strings}")
print(f"{file1} 中独有的字符串: {unique_strings_file1}")
print(f"{file2} 中独有的字符串: {unique_strings_file2}")
# 传入两个文件路径进行比较
compare_text_files('file1.txt', 'file2.txt')
请确保将file1.txt
和file2.txt
替换为实际的文件路径。这个示例代码将比较两个文本文件中的字符串,并输出共同字符串以及每个文件独有的字符串。