2 个文件的 Python difflib,行号不正确

标签 python python-2.7 difflib

我必须在 Python 中比较 2 个文件,并且我正在使用 difflib 。我分别尝试了 ndiff然后用 unified_diff 。根据示例here,这两个文件的内容很简单。 :

File_1.txt:

User1 US
User2 US
User3 US

File_2.txt:

User1 US
User2 US
User3 NG

这是适合我的代码(没有正确的行号):

import difflib
import sys

def dif_wr(d):
    for i,line in enumerate(d):
        sys.stdout.write('{} {}' .format(i+1,line))

# Method 1
with open('File_1.txt', 'r') as h0:
    with open('File_2.txt', 'r') as h1:
        dif = difflib.unified_diff(h0.readlines(),\
                                   h1.readlines(),\
                                   fromfile='File_1.txt',tofile='File_2.txt')
dif_wr(dif)

# Method 2
with open('File_1.txt','r') as fl1, open('File_2.txt','r') as fl2:
    dif2 = difflib.ndiff(fl1.readlines(),fl2.readlines())
dif_wr(dif2)

输出是:

1 --- File_1.txt
2 +++ File_2.txt
3 @@ -1,3 +1,3 @@
4  User1 US
5  User2 US
6 -User3 US7 +User3 NG1   User1 US
2   User2 US
3 - User3 US4 ?       ^^
5 + User3 NG6 ?       ^^

行号似乎不正确。看起来他们是从第 4 行开始的,这是错误的行。

问题

有没有办法在输出中获得正确的行号?

最佳答案

unified_diff 的文档说它需要一个参数n:

Unified diffs are a compact way of showing just the lines that have changed plus a few lines of context. The changes are shown in an inline style (instead of separate before/after blocks). The number of context lines is set by n which defaults to three. The number of context lines is set by n which defaults to three.

此外,参数lineterm:

For inputs that do not have trailing newlines, set the lineterm argument to "" so that the output will be uniformly newline free.

要获得所需的输出,您需要取下行终止符,然后将它们重新添加到输出中。您还需要将上下文行设置为零:

import difflib
import sys    

def dif_wr(d):
    for i, line in enumerate(d):
        sys.stdout.write('{} {}\n'.format(i + 1, line))

一些使用字符串而不是文件的示例代码:

from StringIO import StringIO

file1 = """User1 US
User2 US
User3 US"""

file2 = """User1 US
User2 US
User3 NG"""

dif2 = difflib.unified_diff(StringIO(file1).readlines(),
                            StringIO(file2).readlines(),
                            fromfile='File_1.txt',
                            tofile='File_2.txt',
                            n=0,
                            lineterm="")
dif_wr(dif2)

输出:

1 --- File_1.txt
2 +++ File_2.txt
3 @@ -3,1 +3,1 @@
4 -User3 US
5 +User3 NG

关于2 个文件的 Python difflib,行号不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43213344/

相关文章:

python - 将文本绘制到图像时出现字体错误

python - 比较 Python 中的模块。好的,但是为什么呢?

python - 在 Synapse 的 SQL 数据库中保存 PySpark 数据帧时出现错误 "IllegalArgumentException: KrbException: Cannot locate default realm"

Python Difflib - 如何使用 "Change"Op 获取 SDiff 序列

python - 如何在没有滚动条的情况下将 difflib.HtmlDiff 的 html 输出放入一个窗口中

python - 集成 Rails 和 Python

python - 基于列名的子集结构化数组

python - 在 Python 中编辑输出

python - difflib 输出很奇怪,在每个字符上添加了额外的空格

python - 绑定(bind)到 Enter 的 Tkinter 按钮立即执行