根据线的位置返回不同的值

different values returned depending on where the line is

我正在研究如何使用 ndiff 检查两个文本文件之间的差异,并计算找到了多少差异。在某个时候,我发现我收到了两个不同的值,具体取决于代码行的编写位置...

谁能指出我在这里做错了什么?

我敢肯定这一定是一件非常愚蠢的事情。谢谢!

这是代码和输出...

import difflib

text1 = open('file1.txt', encoding="utf8").readlines()
text2 = open('file2.txt', encoding="utf8").readlines()
print("Showing Data")
print("text1 => " + str(text1))
print("text2 => " + str(text2))
print("DONE!")
print("***********************************************************************")
print("Messing with ndiff")
diff_count = difflib.ndiff(text1, text2)
print("What is in diff_count? " + str(list(diff_count)))
print("Size of List =>>>" + str(len(list(diff_count))))
print("DONE!")
print("***********************************************************************")
print("Messing with ndiff II")
diff_count = difflib.ndiff(text1, text2)
print("Size of List =>>>" + str(len(list(diff_count))))
print("What is in diff_count? " + str(list(diff_count)))
print("DONE!")
print("***********************************************************************")

并且输出...

Showing Data
text1 => ['opentechguides website contains\n', 'tutorials and howto articles\n', 'on topics such as Linux\n', 'Windows, databases etc.,']
text2 => ['opentechguides website contains\n', 'tutorials and howto articles\n', '\n', 'on topics such as Linux\n', 'Windows, databases , networking\n', 'programming and web development.']
DONE!
***********************************************************************
Messing with ndiff
What is in diff_count? ['  opentechguides website contains\n', '  tutorials and howto articles\n', '+ \n', '  on topics such as Linux\n', '- Windows, databases etc.,', '?                      ^^^\n', '+ Windows, databases , networking\n', '?                    +++  ^^^^^^^^\n', '+ programming and web development.']
Size of List =>>>0
DONE!
***********************************************************************
Messing with ndiff II
Size of List =>>>9
What is in diff_count? []
DONE!
***********************************************************************

Python 中的某些对象只能迭代一次。如果您尝试第二次迭代它们,那么它们将给出零个元素。示例:

>>> x = iter([1,2,3,4])
>>> list(x)
[1, 2, 3, 4]
>>> list(x)
[]

我怀疑 diff_count 就是这样一个对象。如果你对它调用 list 两次,第一次它 returns 一个包含 9 个元素的列表,第二次它 returns 一个空列表。这解释了您的两个代码部分中的差异。第一个代码部分显示列表的 9 个元素并显示长度为零,因为对象在 len 调用时已耗尽。第二个代码部分显示长度为 9 并显示列表的 0 个元素,因为对象在 str(list(diff_count)) 调用时已耗尽。

如果你想迭代diff_count多次,那么exactly once将它转换成可以多次迭代的类型,然后迭代它。

diff_count = difflib.ndiff(text1, text2)
seq = list(diff_count)
print("What is in diff_count? " + str(seq))
print("Size of List =>>>" + str(len(seq)))

ndiff returns a generator,不是列表:

return a Differ-style delta (a generator generating the delta lines)

因此,第一次遍历得到一个合理的值,第二次什么也得不到。解决方法是在第一次获取时将其设为列表,然后多次使用该列表:

diff_count = list(difflib.ndiff(text1, text2))