- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我想使用 Google's Diff Match Patch APIs 在 Python 中编写一个简单的 diff 应用程序.我是 Python 的新手,所以我想要一个示例,说明如何使用 Diff Match Patch API 对两段文本进行语义比较。我不太确定如何使用 diff_match_patch.py
文件以及从中导入什么。非常感谢您的帮助!
此外,我尝试使用 difflib , 但我发现它对于比较差异很大的句子是无效的。我使用的是 ubuntu 12.04 x64。
最佳答案
谷歌的 diff-match-patch API对于所有实现它的语言(Java、JavaScript、Dart、C++、C#、Objective C、Lua 和 Python 2.x 或 python 3.x)都是一样的。因此,人们通常可以使用目标语言以外的其他语言的示例片段来确定各种差异/匹配/补丁任务需要哪些特定的 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)
关于 diff-match-patch 的“语义”处理
请注意,这种处理有助于向人类观众展示差异,因为它往往会通过避免不相关的文本重新同步来生成较短的差异列表(例如,当两个不同的单词恰好在它们的中间有共同的字母时)。然而,产生的结果远非完美,因为这种处理只是基于差异长度和表面模式等的简单启发式方法,而不是基于词典和其他语义级设备的实际 NLP 处理。
例如,textA
和 textB
上面使用的值为 diffs
生成以下“之前和之后的 diff_cleanupSemantic”值数组
[(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() 修复为只有两个编辑,很好地挑出不同的 sems 'blue' 和 '红色'。
但是,如果我们有,例如</p>
textA = "stackoverflow is cool"
textb = "so is very cool"
生成的前/后数组是:
[(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')]
这表明与 before 相比,所谓的 after 语义改进可能会被过度“折磨”。例如,请注意前导“s”是如何保持匹配的,以及添加的“very”词是如何与“is cool”表达的部分混合的。理想情况下,我们可能会期待类似
[(-1, 'stackoverflow'), (1, 'so'), (0, ' is '), (-1, 'very'), (0, ' cool')]
关于python - 为 Python 2/3 实现 Google 的 DiffMatchPatch API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16075864/
google DiffMatchPatch 的正则表达式是否为 (A*|B*|C*|D*)* 形式? private static final String TAG_REGEX = "])*>"; /
我想使用 Google's Diff Match Patch APIs 在 Python 中编写一个简单的 diff 应用程序.我是 Python 的新手,所以我想要一个示例,说明如何使用 Diff
我是一名优秀的程序员,十分优秀!