Google的 diff-match-patch API 对于所实现的所有语言都是相同的(Java,Javascript,Dart,C ++,C#,Objective
C,Lua和Python 2.x或python 3.x)。因此,通常可以使用目标语言以外的其他语言的示例代码片段来确定各种diff / match /
patch任务需要哪些特定的API调用。
在简单的“语义”比较的情况下,这就是您需要的
import diff_match_patchtextA = "the cat in the red hat"textB = "the feline in the blue hat"#create a diff_match_patch objectdmp = diff_match_patch.diff_match_patch()# Depending on the kind of text you work with, in term of overall length# and complexity, you may want to extend (or here suppress) the# time_out featuredmp.Diff_Timeout = 0 # or some other value, default is 1.0 seconds# All 'diff' jobs start with invoking diff_main()diffs = dmp.diff_main(textA, textB)# diff_cleanupSemantic() is used to make the diffs array more "human" readabledmp.diff_cleanupSemantic(diffs)# and if you want the results as some ready to display HMTL snippethtmlSnippet = dmp.diff_prettyHtml(diffs)
关于 diff-match-patch的“ 语义 ”处理一词,
请注意,这种处理有助于将差异呈现给人类观看者,因为它倾向于通过避免文本的不相关重新同步来产生较短的差异列表(例如,两个不同的词恰好在中间有共同的字母)。但是,产生的结果远非完美,因为此处理只是基于差异长度和表面图案等的简单启发式处理,而不是基于词典和其他语义级别设备的实际NLP处理。
例如,
textA与
textB值时使用上述产生下面的“之前和之后的-diff_cleanupSemantic”值的
diffs阵列
[(0, 'the '), (-1, 'cat'), (1, 'feline'), (0, ' in the '), (-1, 'r'), (1, 'blu'), (0, 'e'), (-1, 'd'), (0, ' hat')][(0, 'the '), (-1, 'cat'), (1, 'feline'), (0, ' in the '), (-1, 'red'), (1, 'blue'), (0, ' hat')]
真好!红色和蓝色通用的字母“
e”使diff_main()将文本的该区域视为四个编辑,但是cleanupSemantic()仅作为两个编辑而修复,很好地将不同的色块“
blue”和“红’。
但是,例如,如果有
textA = "stackoverflow is cool"textb = "so is very cool"
产生的before / after数组是:
[(0, 's'), (-1, 'tack'), (0, 'o'), (-1, 'verflow'), (0, ' is'), (1, ' very'), (0, ' cool')][(0, 's'), (-1, 'tackoverflow is'), (1, 'o is very'), (0, ' cool')]
这表明,与 以前 相比,所谓的语义改进 后 可能会受到不适当的“折磨” 。请注意,例如,如何将前导“
s”保留为匹配项,以及如何将添加的“非常”一词与“很酷”表达的一部分混合在一起。理想情况下,我们可能希望 __
[(-1, 'stackoverflow'), (1, 'so'), (0, ' is '), (-1, 'very'), (0, ' cool')]



