我有两个文本,文本 A 和文本 B。文本 B 不是文本 A 的精确副本,它有很多不在文本 A 中的特殊字符,但从技术上讲,它是相同的文本。我需要比较字符串并将文本 B 中的对应项映射到文本 A 中的对应项。
文本不是英文的,也不容易翻译成英文,所以下面的例子只是为了说明一些问题。
文本 A 中的某些词不在文本 B 中,但文本 B 中的所有词都应在文本 A 中:
text_a = "he experienced déjà vu"
text_b = ['he', 'experienced']
文本 B 中的某些词使用与文本 A 不同的字符,但它们是相同的词:
text_a = "she owns & runs the cafe florae"
text_b = ['she', 'owns', 'and', 'runs', 'the', 'cefé', 'floræ']
文本 B 中的单词通常按正确的顺序排列,但并非总是如此:
text_a = "an uneasy alliance"
text_b = ['uneasy', 'alliance', 'an']
文本 B 中的一些单词是由较小的组件组成的,这些组件也包含在文本 B 中,而这些较小的组件是不必要的:
text_a = "we should withdraw our claim"
text_b = ['we', 'should', 'with', 'draw', 'withdraw', 'our', 'claim']
文本 A 中的某些词由文本 B 中的两个或多个词表示:
text_a = "they undercut their competitors"
text_b = ['they', 'under', 'cut', 'their', 'competitors']
我想要做的是用文本 B 中的对应词替换文本 A 中的单词。为此,我需要编写一个函数来匹配两个文本之间的单词。
我已经尝试编写一个函数,该函数使用库中的edit distance
方法和一些正则表达式来比较字符串。nltk
这只做得不错,所以我研究了使用sequence alignment
库中的技术,例如biopython
,但我无法理解这些。
特别是,在使用编辑距离时,很难将诸如“under”和“cut”之类的词与“undercut”匹配,同时也避免了短字符串中的错误。这是因为在一个包含相似标记的句子中,比如“to”和“tu”,这些标记与“tú”之类的东西有相同的编辑距离,理论上它们是同样有效的候选者,尽管这里明显的匹配是“tu” ',而不是'到'。
是否有任何高度准确的方法来匹配文本 A 中文本 B 中的字符串?我想得到如下输出:
text_a = "the cafe florae undercut their competitors then withdrew their claim"
text_b = ['the', 'café', 'floræ', 'under', 'cut', 'their', 'competitors', 'then',
'with', 'drew', 'withdrew', 'their', 'claim']
match_list = some_matchfunc(text_a, text_b)
print(match_list)
[['the', 'the'], ['cafe', 'café'], ['florae', 'floræ'], ['undercut', 'under'],
['undercut', 'cut'], ['their', 'their'], ['competitors', 'competitors'], ['then', 'then'],
['withdrew', 'withdrew'], ['their', 'their'], ['claim', 'claim']]
理想情况下,这还将包括文本 A 中每个匹配单词的开头和结尾的索引,以避免混淆,例如下面出现两次的单词“their”:
[['the', [0, 3] 'the'], ['cafe', [4, 8] 'café'], ['florae', [9, 15] 'floræ'],
['undercut', [16, 24], 'under'], ['undercut', [16, 24], 'cut'], ['their', [25, 30], 'their'],
['competitors', [31, 42], 'competitors'], ['then', [43, 47], 'then'], ['withdrew', [48, 56], 'withdrew'],
['their', [57, 62], 'their'], ['claim', [63, 68], 'claim']]
如上所述,文本不是英文的,翻译它以使用 NLP 技术比较单词实际上并不可行,因此它确实需要基于字符串比较。我认为肯定有一些方法或库已经存在,它采用比我使用 RegEx 和编辑距离想出的更有效的序列比对算法,但我找不到。
有人知道用于比较字符串以实现此结果的高度准确的方法吗?