用python写一个对码工具
时间: 2023-09-02 18:06:10 浏览: 42
对码工具可以实现两段文本的对比,找出不同之处。下面是用 Python 编写的一个简单对码工具。
```python
def compare_text(text1, text2):
"""
对比两段文本,返回不同之处的行号和内容
"""
# 将文本按行分割成列表
lines1 = text1.split('\n')
lines2 = text2.split('\n')
# 计算行数
num_lines1 = len(lines1)
num_lines2 = len(lines2)
# 取行数较小的文本作为基准
if num_lines1 < num_lines2:
base_lines = lines1
comp_lines = lines2
else:
base_lines = lines2
comp_lines = lines1
# 对比每行文本
diff_lines = []
for i, line in enumerate(base_lines):
if line != comp_lines[i]:
diff_lines.append((i+1, line, comp_lines[i]))
# 返回不同之处的行号和内容
return diff_lines
```
使用示例:
```python
text1 = '''Hello, world!
This is a test.
'''
text2 = '''Hello, world!
This is not a test.
'''
diff_lines = compare_text(text1, text2)
for line in diff_lines:
print('Line {}:'.format(line[0]))
print(' Text1: {}'.format(line[1]))
print(' Text2: {}'.format(line[2]))
```
输出结果:
```
Line 2:
Text1: This is a test.
Text2: This is not a test.
```
该对码工具对比两段文本,返回不同之处的行号和内容。在使用时,只需要传入两段文本即可。