-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,445
  • 5
  • 38
  • 65

2 Answers2

1
found=re.finditer(r"\b"+word+r"\b", text)
#         raw string here ___^
Toto
  • 89,455
  • 62
  • 89
  • 125
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
  • 88,541
  • 4
  • 65
  • 105