38 lines
1.5 KiB
Python
38 lines
1.5 KiB
Python
![]() |
def compare_strings(str1, str2):
|
||
|
# 清理字符串:去除首尾空白,按换行分割后去除每行空白,按逗号分割
|
||
|
list1 = [item.strip() for item in str1.strip().split('\n') if item.strip()]
|
||
|
list1 = [sub_item.strip() for item in list1 for sub_item in item.split(',') if sub_item.strip()]
|
||
|
list2 = [item.strip() for item in str2.strip().split('\n') if item.strip()]
|
||
|
list2 = [sub_item.strip() for item in list2 for sub_item in item.split(',') if sub_item.strip()]
|
||
|
|
||
|
# 找出差异
|
||
|
diff1 = [item for item in list1 if item not in list2] # str1 比 str2 多的元素
|
||
|
diff2 = [item for item in list2 if item not in list1] # str2 比 str1 多的元素
|
||
|
|
||
|
# 构建输出
|
||
|
result = []
|
||
|
if diff1:
|
||
|
result.append(f"第一个字符串比第二个字符串多了 {len(diff1)} 个元素:")
|
||
|
result.extend(diff1) # 每个元素占一行
|
||
|
if diff2:
|
||
|
result.append(f"第二个字符串比第一个字符串多了 {len(diff2)} 个元素:")
|
||
|
result.extend(diff2) # 每个元素占一行
|
||
|
|
||
|
# 返回结果
|
||
|
return '\n'.join(result) if result else "两个字符串相同"
|
||
|
|
||
|
|
||
|
# 从文件读取数据
|
||
|
try:
|
||
|
with open('str1.txt', 'r', encoding='utf-8') as f:
|
||
|
str1 = f.read()
|
||
|
with open('str2.txt', 'r', encoding='utf-8') as f:
|
||
|
str2 = f.read()
|
||
|
|
||
|
# 运行比较
|
||
|
print(compare_strings(str1, str2))
|
||
|
|
||
|
except FileNotFoundError as e:
|
||
|
print(f"错误:找不到文件 {e.filename}")
|
||
|
except Exception as e:
|
||
|
print(f"发生错误:{str(e)}")
|