Python:动态组合的正则表达式在findi中不起作用

2024-05-23 18:52:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在一个句子中找到匹配的词,并动态地提供这个词。我编写了以下代码,可用于该示例:

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

但由于我需要目标单词作为输入,而这个输入是未知的,所以我更改了如下代码,它停止了工作:

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

我应该如何更正我的代码?谢谢


Tags: andof代码textinrethisprint
2条回答
found=re.finditer(r"\b"+word+r"\b", text)
#         raw string here ___^

只需使用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")

相关问题 更多 >