如何匹配句子中的字符串

How to match a string in a sentence

我想检查句子中是否存在特定字符串。为此,我使用了简单的代码

subStr = 'joker'
Sent = 'Hello World I am Joker'

if subStr.lower() in Sent.lower():
    print('found')

这是一种简单直接的方法,但是当句子显示为

时它会失败

hello world I am Jo ker

hello world I am J oker

当我从 PDF 文件中解析句子时,到处都是一些不必要的空格。

解决此问题的一种简单方法是删除句子中的所有空格并查找子字符串匹配项。我想知道其他人对此的想法,我应该坚持这种方法还是寻找其他替代方法。

试试这个。这可能会在某处意外中断。但对于您的用例,这可能有效

In [1]: Sent = 'Hello World I am Joker'

In [3]: subStr = 'Joker'

In [4]: if subStr in Sent.replace(' ', ''):
   ...:     print("Do something")
   ...:     
Do something

你可以使用正则表达式:

import re
word_pattern = re.compile(r'j\s*o\s*k\s*e\s*r', re.I)
sent = 'Hello World I am Joker'
if word_pattern.search(sent):
    print('found')

我希望这有效

对于小字符串,这比 replace 更有效,对于大字符串则更昂贵。它不会处理模棱两可的情况,例如'to day' 对比 'today'.

subStr in ''.join(Sent.split()).lower()  # True

您提出的方法 - 删除空格 - 似乎简单而有效(在一些简单的测试中,比其他建议快两到十倍)。但是,如果您需要最大程度地减少误报,那么使用正则表达式方法可能会更好。您可以添加单词边界以避免部分单词匹配,并检查匹配的子字符串以查看是否有任何空格可能是真实空格,也许通过与规范单词列表匹配。

>>> sentence = 'Were the fields ever green? - they were never green.'
>>> target = 'evergreen'
>>> pattern = re.compile(r'\b' + '\s*'.join(target) + r'\b')
>>> pattern.findall(sentence) # only one match because of \b
['ever green']
>>> matching_words = pattern.findall(sentence)[0].split()
>>> all(word in dictionary for word in matching_words)
True