[Python] Python Regex: find all possible forms of a word in text with pattern

Discussão em 'Python' iniciado por Stack, Julho 3, 2025.

  1. Stack

    Stack Membro Participativo

    I want to find all possible combinations of a list of words in a text (plural, singular, prefixed, etc.). Currently I defined the following function that uses a regex pattern to find a word in my text. But it doesn't match the word "nation" in the last sentence in my text (" who is a nation.") unless I replace the period with space (" who is a nation "). Similarly, it doesn't match the words "nationality" or "nations". I want to use a pattern so I can expand my code to match any words in a list of selected words in the text. Is there a way to check if these matchings exist in the text with a regex pattern?

    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

    Continue reading...

Compartilhe esta Página