Python - 获取字符串之间的差异

Rek*_*vni 6 python difflib python-2.7

从两个多线字符串中获得差异的最佳方法是什么?

a = 'testing this is working \n testing this is working 1 \n'
b = 'testing this is working \n testing this is working 1 \n testing this is working 2'

diff = difflib.ndiff(a,b)
print ''.join(diff)
Run Code Online (Sandbox Code Playgroud)

这会产生:

  t  e  s  t  i  n  g     t  h  i  s     i  s     w  o  r  k  i  n  g     
     t  e  s  t  i  n  g     t  h  i  s     i  s     w  o  r  k  i  n  g     1     
+  + t+ e+ s+ t+ i+ n+ g+  + t+ h+ i+ s+  + i+ s+  + w+ o+ r+ k+ i+ n+ g+  + 2
Run Code Online (Sandbox Code Playgroud)

准确得到的最佳方法是什么:

testing this is working 2

正则表达式会在这里解决吗?

Kau*_* NP 6

最简单的 Hack,归功于@Chris,使用split().

注意:您需要确定哪个是更长的字符串,并将其用于拆分。

if len(a)>len(b): 
   res=''.join(a.split(b))             #get diff
else: 
   res=''.join(b.split(a))             #get diff

print(res.strip())                     #remove whitespace on either sides
Run Code Online (Sandbox Code Playgroud)

# 驱动值

IN : a = 'testing this is working \n testing this is working 1 \n' 
IN : b = 'testing this is working \n testing this is working 1 \n testing this is working 2'

OUT : testing this is working 2
Run Code Online (Sandbox Code Playgroud)

编辑:感谢@ekhumoro使用 的另一个hack replace,不需要任何join计算。

if len(a)>len(b): 
    res=a.replace(b,'')             #get diff
else: 
    res=b.replace(a,'')             #get diff
Run Code Online (Sandbox Code Playgroud)

  • `b.replace(a, '')` 更简单、更快、更有意义。 (2认同)

God*_*629 6

a = 'testing this is working \n testing this is working 1 \n'
b = 'testing this is working \n testing this is working 1 \n testing this is working 2'

splitA = set(a.split("\n"))
splitB = set(b.split("\n"))

diff = splitB.difference(splitA)
diff = ", ".join(diff)  # ' testing this is working 2, more things if there were...'
Run Code Online (Sandbox Code Playgroud)

本质上使每个字符串成为一组行,并取集差异 - 即 B 中所有不在 A 中的东西。然后取该结果并将其全部连接成一个字符串。

编辑:这是表达@ShreyasG 所说内容的一种复杂方式 - [x for x if x not in y] ...


小智 5

这基本上是@Godron629 的答案,但由于我无法发表评论,因此我将其发布在这里并稍作修改:更改differencesymmetric_difference以便集合的顺序无关紧要。

a = 'testing this is working \n testing this is working 1 \n'
b = 'testing this is working \n testing this is working 1 \n testing this is working 2'

splitA = set(a.split("\n"))
splitB = set(b.split("\n"))

diff = splitB.symmetric_difference(splitA)
diff = ", ".join(diff)  # ' testing this is working 2, some more things...'
Run Code Online (Sandbox Code Playgroud)