-1
import diff_match_patch
old_string = """I'm selfish, impatient and a little insecure. I make mistakes,
I am out of control and at times hard to handle. But if you can't handle me at my worst,
then you sure as hell don't deserve me at my best."""
new_string = """I'm selfish, impatient and a little secure. I don't make mistakes,
I am out of control and at times hard to handle difficult things. But if you can't handle me at my worst,
then you sure as hell don't deserve me at my best."""
class SideBySideDiff(diff_match_patch.diff_match_patch):
def old_content(self, diffs):
"""
Returns HTML representation of 'deletions'
"""
html = []
for (flag, data) in diffs:
text = (data.replace("&", "&")
.replace("<", "<")
.replace(">", ">")
.replace("\n", "<br>"))
if flag == self.DIFF_DELETE:
html.append("""<del style=\"background:#ffe6e6;
\">%s</del>""" % text)
elif flag == self.DIFF_EQUAL:
html.append("<span>%s</span>" % text)
return "".join(html)
def new_content(self, diffs):
"""
Returns HTML representation of 'insertions'
"""
html = []
for (flag, data) in diffs:
text = (data.replace("&", "&")
.replace("<", "<")
.replace(">", ">")
.replace("\n", "<br>"))
if flag == self.DIFF_INSERT:
html.append("""<ins style=\"background:#e6ffe6;
\">%s</ins>""" % text)
elif flag == self.DIFF_EQUAL:
html.append("<span>%s</span>" % text)
return "".join(html)
diff_obj = SideBySideDiff()
result = diff_obj.diff_main(old_string, new_string)
diff_obj.diff_cleanupSemantic(result)
diffs = diff_obj.diff_main(old_string, new_string)
old_record = diff_obj.old_content(result)
new_record = diff_obj.new_content(result)
http://agiliq.com/blog/2014/05/google-diff-match-patch-library/
的例子中,我似乎無法它顯示在HTML文件並排結果側。我怎麼能解決這個問題?
只是爲了確保:您知道它是html,所以您必須在網絡瀏覽器中顯示它? 「似乎無法讓它工作」並沒有多大的意義。 – then0rTh
燁我知道輸出將在HTML中。我對difflib模塊做了同樣的事情,但不知道如何用Google的diff_match_patch做到這一點 – PRIME