python - 具有可迭代值的正则表达式函数
问题描述
所以我有一些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 示例的单词:
猫,一个,
解决方案
在这种情况下,您应该使用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''
字符串中间调用变量/查找。
推荐阅读
- java - 为什么这些方法编译成汇编?
- javascript - 如何更改:Fullcalendar 生成 GET 请求
- ios - 具有相同 xib 的两个不同 UITableViewCell
- cygwin - -bash:cygrunsrv:找不到命令
- c# - WCF服务:调用第一个函数,从它返回,然后调用第二个函数在后台工作
- asp.net-mvc - 用户密码的 MVC 管理员重置
- css - Wordpress 将图像宽度设置为 100% 并将最大宽度设置为插入宽度
- vue.js - Vuex Mutation 未正确设置状态
- opengl-es - WebGL2 是否自动内置了抗锯齿功能?
- mysql - 我写了一个MYSQL程序,语法有错误,不知道正确的语法