因此,使用 Python 的difflib,我可以生成两个字符串的差异:
foo = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.\n Nullam sed orci lobortis lectus bibendum vehicula.\n Integer iaculis eros porttitor velit porttitor scelerisque.\n Nunc venenatis nibh.'.splitlines()
bar = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.\n Mauris placerat, odio ut viverra gravida, elit leo tincidunt nisi, a pellentesque velit arcu id magna.\n Integer iaculis eros porttitor velit porttitor scelerisque.\n Nunc venenatis nibh.'.splitlines()
diff = difflib.unified_diff(foo, bar, lineterm='')
然后,如果我们愿意,我们可以检查差异:
>>> print '\n'.join(diff)
---
+++
@@ -1,4 +1,4 @@
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
- Nullam sed orci lobortis lectus bibendum vehicula.
+ Mauris placerat, odio ut viverra gravida, elit leo tincidunt nisi, a pellentesque velit arcu id magna.
Integer iaculis eros porttitor velit porttitor scelerisque.
Nunc venenatis nibh.
这就是我卡住的地方。如何将该差异应用于字符串foo
以产生字符串bar
?