从两个多行字符串中获取差异的最佳方法是什么?
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
精确获取的最佳方法是什么:
testing this is working 2
?正则表达式将是这里的解决方案吗?
最佳答案
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中的东西。然后取该结果并将其全部连接到一个字符串中。
编辑:这是一种表达@ShreyasG所说的方式的混淆方式-[如果x不在y中,则x用于x] ...
关于Python-得到字符串之间的区别,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46453075/