Python-得到字符串之间的区别 [英] Python - getting just the difference between strings

查看:66
本文介绍了Python-得到字符串之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从两个多行字符串中获取差异的最好方法是什么?

What's the best way of getting just the difference from two multiline strings?

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)

这将产生:

  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

获得准确的最好方法是什么?

What's the best way of getting exactly:

testing this is working 2?

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

Would regex be the solution here?

推荐答案

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...'

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

Essentially making each string a set of lines, and taking the set difference - i.e. All things in B that are not in A. Then taking that result and joining it all into one string.

这是一种表达@ShreyasG所说的方式的迷惑方式-[如果x不在y,则x用于x] ...

This is a conveluded way of saying what @ShreyasG said - [x for x if x not in y]...

这篇关于Python-得到字符串之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆