-1

I want to find matching words in a sentence, with the word being dynamically supplied. I wrote the following code which works with the example:

text="Algorithmic detection of misinformation and disinformation Gricean perspectives"
found=re.finditer(r"\bdetection\b", text)
for i in found:
    print("found") #this line prints exactly once

But since I need the target word as input that is not known a-priori, I changed the code like below, and it stopped working:

text="Algorithmic detection of misinformation and disinformation Gricean perspectives"
word="detection" #or passed by other functions etc.
found=re.finditer(r"\b"+word+"\b", text)
for i in found:
    print("found") #this line does not print in this piece of code

How should I correct my code please? Thanks

Ziqi
  • 2,199
  • 4
  • 32
  • 58

2 Answers2

1
found=re.finditer(r"\b"+word+r"\b", text)
#         raw string here ___^
Toto
  • 86,179
  • 61
  • 85
  • 118
1

Simply with Raw f-strings:

text = "Algorithmic detection of misinformation and disinformation Gricean perspectives"
word = "detection"  # or passed by other functions etc.
pat = re.compile(fr"\b{word}\b")   # precompiled pattern
found = pat.finditer(text)
for i in found:
    print("found")
RomanPerekhrest
  • 75,918
  • 4
  • 51
  • 91