python - 如何使用正则表达式在文件中找到一些单词?
问题描述
我有很多文件,需要将它们分类为出现的单词。
例如)[..murder..murderAttempted..] 或 [murder, crimeAttempted] 等。
我试过这段代码。但并不是所有的都出来了。所以我想在由“[]”包围的文件中出现“murder”和“murderAttmpted”。
def func(root_dir):
for files in os.listdir(root_dir):
pattern = r'\[.+murder.+murderAttempted.+'
if "txt" in files:
f = open(root_dir + files, 'rt', encoding='UTF8')
for i, line in enumerate(f):
for match in re.finditer(pattern, line):
print(match.group())
解决方案
This appears to work for me: pattern = r'\[.*murder.*murderAttempted.*\]'
instead of pattern = r'\[.+murder.+murderAttempted.+'
. I believe it returns all occurrences of "murder" and "murderAttempted" in files surrounded by "[]". The +
requires 1 or more occurrence whereas *
could have 0. Also note the addition of the end \]
. This ensures you only capture strings that are enclosed in brackets.
推荐阅读
- flutter - 如何使 PageView 自动播放并且每个项目都有特定的持续时间?
- python - 如何修改我的代码以便将我从 Python 终端上的代码执行的输出提取到 fasta 文件?
- docker-compose - Docker compose抛出无法执行脚本docker-compose
- javascript - 如何使用存储为字符串的日期查询 mongodb
- python - 无法隔离字符串的元素以进行转换和完成添加
- tensorflow - AttributeError:“JpegImageFile”对象没有“读取”属性
- sql - 如何在 PostgreSQL 10 中更改文件名
- python - 停止列表在父类中是静态的
- java - Grails 唯一域约束
- vue.js - 如何在 vue js 中这样打印?