Python 正则表达式:在具有模式的文本中查找单词的所有可能形式
Python Regex: find all possible forms of a word in text with pattern
我想找到文本中单词列表的所有可能组合(复数、单数、前缀等)。目前我定义了以下函数,它使用正则表达式模式在我的文本中查找单词。但它与我文本中最后一句话(“who is a nation.”)中的“nation”一词不匹配,除非我将句点替换为 space(“who is a nation”)。同样,它也不匹配“国籍”或“民族”等词。我想使用一种模式,这样我就可以扩展我的代码以匹配文本中选定单词列表中的任何单词。有没有办法检查这些匹配项是否存在于具有正则表达式模式的文本中?
text = '''
we are the natio
we love other nations.
other nationalities are good too, we are that. who is a nation.
'''
def WordsinSentence(word,sentence):
pattern = re.compile(' '+word+' |^'+word+' | '+word+' $')
# stem = tokenize_and_stem(sentence)
# stemmed_sent = ' '.join(stem)
if re.search(pattern,sentence.lower()):
return True
使用正则表达式 'findall' 方法获取所有匹配项。
def WordsinSentence(word,sentence):
pattern = re.compile(word)
found = re.findall(pattern,sentence.lower())
if found:
return True
else:
return False
在此处了解更多信息:Python Regex findall
我想找到文本中单词列表的所有可能组合(复数、单数、前缀等)。目前我定义了以下函数,它使用正则表达式模式在我的文本中查找单词。但它与我文本中最后一句话(“who is a nation.”)中的“nation”一词不匹配,除非我将句点替换为 space(“who is a nation”)。同样,它也不匹配“国籍”或“民族”等词。我想使用一种模式,这样我就可以扩展我的代码以匹配文本中选定单词列表中的任何单词。有没有办法检查这些匹配项是否存在于具有正则表达式模式的文本中?
text = '''
we are the natio
we love other nations.
other nationalities are good too, we are that. who is a nation.
'''
def WordsinSentence(word,sentence):
pattern = re.compile(' '+word+' |^'+word+' | '+word+' $')
# stem = tokenize_and_stem(sentence)
# stemmed_sent = ' '.join(stem)
if re.search(pattern,sentence.lower()):
return True
使用正则表达式 'findall' 方法获取所有匹配项。
def WordsinSentence(word,sentence):
pattern = re.compile(word)
found = re.findall(pattern,sentence.lower())
if found:
return True
else:
return False
在此处了解更多信息:Python Regex findall