将difflib.compare与python一起使用来比较两个文本文件。我知道比较基本上返回一个字符串列表。当字符串对于第一个文本文件是唯一的时,它在字符串前面放置一个“ - ”,当字符串对第二个文本文件是唯一的时,它在字符串前面放置一个“+”。
我的问题是我正在尝试编写一些代码来确定要保留的字符串。我开始在每个字符串中寻找“ - ”,如果我找到它,然后我执行了一些逻辑来确定我是否要使用该字符串。如果我不打算使用它,那么我或者向下看一两行“+”。
在我的几乎所有情况下,“ - ”行都在“+”行之前。但现在我得到“+”行在“ - ”行之前的实例。这会丢掉我的代码,因为它无法找到写入输出文本文件的正确行。有没有人知道字符串如何写入数组背后的逻辑是基于最先出现的行号?
ex//
majority of the time out put is this:
"- color: #ffffff;"
"+ color: #785642;"
but rarely it does come out the opposite:
"+ color: #785642;"
"- color: #ffffff;"
答案 0 :(得分:0)
DIFFERENCE_OUTPUT = []
def find_differences(list1, list2):
list1 = sorted(list1)
list2 = sorted(list2)
for diff in difflib.ndiff(list1,list2):
DIFFERENCE_OUTPUT.append(diff)
for line in DIFFERENCE_OUTPUT:
if line.startswith("-"):
#I would suggest change the '-' to the name of the file and print line to see what is there
line = line.replace('-','NAME of List')
print(line)
****preform task
elif line.startswith("+"):
****preform task
所有' - '应为list1,所有'+'应为list2。如果你在' - '之前看到'+'表示list2有输出但是list1没有,反之亦然。