首页 文章

如何在一个句子中模糊匹配单词到一个完整单词(并且只有完整单词)?

提问于
浏览
9

大多数commonly misspelled English words在其正确形式的两个或三个印刷错误(替换s,插入i或字母删除d的组合)内 . 即单词对 absence - absense 中的错误可以概括为具有1s,0i和0d .

可以模糊匹配使用to-replace-re regex python module查找单词及其拼写错误 .

下表总结了从一些句子中对一个感兴趣的词进行模糊分段的尝试:

enter image description here

  • Regex1在 sentence 中找到最佳 word 匹配,最多允许2个错误

  • Regex2在 sentence 中找到最佳 word 匹配,在尝试仅操作(我认为)整个单词时最多允许2个错误

  • Regex3在 sentence 中找到最佳 word 匹配,允许最多2个错误,同时仅在(我认为)整个单词上操作 . 我错了 .

  • Regex4在 sentence 中找到最佳 word 匹配,允许最多2个错误,而我(我认为)寻找匹配结束为单词边界

我如何编写一个正则表达式,如果可能的话,在这些单词 - 句子对上消除假阳性和假阴性模糊匹配?

一种可能的解决方案是仅将句子中的单词(由空格包围的字符串或行的开头/结尾)与感兴趣的单词(主要单词)进行比较 . 如果主要单词和句子中的单词之间存在模糊匹配(e <= 2),则从句子中返回该完整单词(并且仅返回该单词) .

代码

将以下数据帧复制到剪贴板:

word                  sentence
0      cub cadet              cub cadet 42
1        plastex              vinyl panels
2            spt  heat and air conditioner
3     closetmaid                closetmaid
4          ryobi           batteries kyobi
5          ryobi       10' table saw ryobi
6  trafficmaster           traffic mast5er

现在用

import pandas as pd, regex
df=pd.read_clipboard(sep='\s\s+')

test=df
test['(?b)(?:WORD){e<=2}']=df.apply(lambda x: regex.findall(r'(?b)(?:'+x['word']+'){e<=2}', x['sentence']),axis=1)
test['(?b)(?:\wWORD\W){e<=2}']=df.apply(lambda x: regex.findall(r'(?b)(?:\w'+x['word']+'\W){e<=2}', x['sentence']),axis=1)
test['(?V1)(?b)(?:\w&&WORD){e<=2}']=df.apply(lambda x: regex.findall(r'(?V1)(?b)(?:\w&&'+x['word']+'){e<=2}', x['sentence']),axis=1)
test['(?V1)(?b)(?:WORD&&\W){e<=2}']=df.apply(lambda x: regex.findall(r'(?V1)(?b)(?:'+x['word']+'&&\W){e<=2}', x['sentence']),axis=1)

将表加载到您的环境中 .

1 回答

  • 2

    '(?b)\m(?:WORD){e<=2}\M'

相关问题