Search key words in a sentence (Python)

Viewed 42

I have following codes:

import re

sentences=['the Research and development cost of the year']
rdterms=['research and development']
rdterms_regex = [re.compile(r'\b' + term + r'\b') 
                    for term in rdterms] 

def rdsentence(sentence:str):
    """Checks whether a sentence is R&D-oriented."""
    for term in rdterms_regex:    
        if term.search(sentence, re.IGNORECASE): 
            return True 
    return False

for sentence in sentences:
    print(rdsentence(sentence))

The purpose of the codes is to detect whether the key word in rdterms (i.e.'research and development') appears in the sentence (i.e 'the Research and development cost of the year').

If the sentence is "the research and development cost of the year"--Current report "True"--Correct.

If the sentence is "the Research and development cost of the year"--Current report "False"--I want it to report "True".

If the sentence is "research and development"--Current report "False"--I want it to report "True".

What's wrong with my codes? Thank you!

1 Answers

Specify re.IGNORECASE when you compile the regex, not in the search:

rdterms_regex = [re.compile(r'\b' + term + r'\b', re.IGNORECASE) 
                    for term in rdterms] 

def rdsentence(sentence:str):
    """Checks whether a sentence is R&D-oriented."""
    for term in rdterms_regex:    
        if term.search(sentence): 
            return True 
    return False
Related