简体   繁体   中英

How to apply the output of python's difflib.unified_diff to the original string?

So, using Python's difflib , I can generate a diff of two strings:

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='')

We can then check out the diff if we so desired:

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

And here's where I'm stuck. How can I apply that diff to string foo to result in string bar ?

If you use ndiff then you can restore the original string using restore

>>> diff = difflib.ndiff(foo, bar)
>>> diff = list(diff)
>>> print ''.join(difflib.restore(diff, 2))
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam sed orci lobortis lectus bibendum baculo mihi. Integer iaculis eros porttitor velit porttitor scelerisque. Nunc venenatis nibh.
>>> ''.join(difflib.restore(diff, 2))==''.join(bar)
True
>>> ''.join(difflib.restore(diff, 1))==''.join(foo)
True
>>> 

Please note since unified diffs usually drops lines that compared equal to begin with it would be almost impossible to restore to the original string. ndiff shows everything, so it would be straight forward to restore the original.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM