【问题标题】:Python Regex: find all possible forms of a word in text with patternPython Regex:在带有模式的文本中查找单词的所有可能形式
【发布时间】:2021-09-23 01:35:40
【问题描述】:

我想查找文本中单词列表的所有可能组合(复数、单数、前缀等)。目前,我定义了以下函数,该函数使用正则表达式模式在文本中查找单词。但它与我文本中最后一句中的“国家”一词(“谁是一个国家。”)不匹配,除非我用空格替换句点(“谁是一个国家”)。同样,它与“国籍”或“民族”一词不匹配。我想使用一种模式,以便我可以扩展我的代码以匹配文本中选定单词列表中的任何单词。有没有办法检查这些匹配是否存在于带有正则表达式模式的文本中?

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

【问题讨论】:

  • 为什么不直接用空格分割单词,然后用in(包含)检查?

标签: python regex pattern-matching


【解决方案1】:

使用正则表达式“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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多