您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

为Python 2/3实现Google的DiffMatchPatch API

为Python 2/3实现Google的DiffMatchPatch API

Google的 对于所实现的所有语言都是相同的(Java,JavaScript,Dart,C ++,C#,ObjectiveC,Lua和Python 2.x或python3.x)。因此,通常可以使用目标语言以外的其他语言的示例代码片段来确定各种diff / match / patch任务需要哪些特定的API调用

在简单的“语义”比较的情况下,这就是您需要的

import diff_match_patch

textA = "the cat in the red hat"
textB = "the feline in the blue hat"

#create a diff_match_patch object
dmp = 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 feature
dmp.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" readable
dmp.diff_cleanupSemantic(diffs)

# and if you want the results as some ready to display HMTL snippet
htmlSnippet = dmp.diff_prettyHtml(diffs)

请注意,这种处理有助于将差异呈现给人类观看者,因为它倾向于通过避免文本的不相关重新同步来产生较短的差异列表(例如,两个不同的词恰好在中间有共同的字母)。但是,产生的结果远非完美,因为此处理只是基于差异长度和表面图案等的简单启发式处理,而不是基于词典和其他语义级别设备的实际NLP处理。 例如,textAtextB值时使用上述产生下面的“之前和之后的-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')]
python 2022/1/1 18:33:01 有300人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶