首页 > 解决方案 > 具有可迭代值的正则表达式函数

问题描述

所以我有一些file,我需要检查我的 dic 中的某些单词是否Count在某些文件行中。

我一开始试过 if Count[j+1] in file[i]: 但没有用,因为例如a字典中的单词会在任何地方触发,等等。

for i in range(lines_number):    
    for j in range(len(Count)):
        words_counter = 0
        if Count[j+1] in file[i]:
            words_counter += 1  

所以我尝试继续使用正则,但我不知道如何放入Count[j+1]正则表达式。

for i in range(lines_number):    
    for j in range(len(Count)):
        words_counter = 0
        if len(re.findall(r '\b Count[j+1] \b', file[i]) > 0:
            words_counter += 1  

句子示例:

一方面,人们在人工选择的过程中故意驯服猫,因为它们是害虫的有用捕食者。

来自 dic 示例的单词:

猫,一个,

标签: pythonregex

解决方案


在这种情况下,您应该使用Literal String Interpolation。所以你的代码看起来像 -

for i in range(lines_number):    
    for j in range(len(Count)):
        words_counter = 0
        if len(re.findall(rf"\b {Count[j+1]} \b", file[i]) > 0:
            words_counter += 1  

这特别允许您在r''字符串中间调用变量/查找。


推荐阅读