发布于 2020-11-05 09:46:38
像这样怎么样?
>>> a = ['cat', 'dog', 'horse']
>>> b = ['cat', 'horse', 'chicken']
>>> comparison = list(l for l in difflib.Differ().compare(a,b) if not l.startswith('?'))
>>> left = [l[2:] if l.startswith((' ', '-')) else '' for l in comparison]
>>> right = [l[2:] if l.startswith((' ', '+')) else '' for l in comparison]
>>> left
['cat', 'dog', 'horse', '']
>>> right
['cat', '', 'horse', 'chicken']
发布于 2015-06-24 21:04:19
我尝试过用difflib.context_diff来做文件比较
diff = difflib.context_diff(fromlines, tolines, fromfile='file1.txt', tofile='file2.txt')
sys.stdout.writelines(diff)
在这种情况下,您的输出将如下所示:
*** file1.txt
--- file2.txt
***************
*** 1,6 ****
! aasdf
qwer
123
! poiu
! xzcv34
xzcv
--- 1,6 ----
! asdf
qwer
+ mnbv
123
! cvnn
xzcv
在这种情况下,您将能够轻松地将每个文件区分开来,但是我不确定您是否会对context_diff的输出感到满意。您还没有提到您将以何种方式使用difflib。
https://stackoverflow.com/questions/31022893
复制相似问题