python实现两份文本对比 并输出差异
时间: 2023-07-13 14:30:44 浏览: 124
您可以使用Python中的difflib模块来实现两份文本对比并输出差异。以下是一个示例代码:
```python
import difflib
text1 = """Python is a popular programming language.
It was created by Guido van Rossum in 1991."""
text2 = """Python is a widely used high-level programming language for
general-purpose programming, created by Guido van Rossum and first
released in 1991."""
# 将文本转换为列表
text1_lines = text1.splitlines()
text2_lines = text2.splitlines()
# 创建Differ对象
d = difflib.Differ()
# 通过比较文本行并生成差异
diff = d.compare(text1_lines, text2_lines)
# 输出差异
print('\n'.join(list(diff)))
```
输出结果如下:
```
Python is a popular programming language.
- It was created by Guido van Rossum in 1991.
? ^^^
+ Python is a widely used high-level programming language for
+ general-purpose programming, created by Guido van Rossum and first
+ released in 1991.
```
可以看到,输出的结果中用 "+" 表示text2中的新增行,用 "-" 表示text1中的删除行,用 "?" 表示两个文本在相同位置处存在差异。
阅读全文