目录文本文件内容正则匹配需求实现与代码无输出问题排查
问题排查与修复方案
现有代码核心错误点
- 语法错误:Python 分支判断关键字为
elif,你代码中的elsif属于拼写错误,会直接触发语法异常导致程序终止运行,这是无输出的首要原因。 - 依赖缺失:代码使用了
re、os模块但未做导入,运行会触发NameError。 - 逻辑完全错位:你需要匹配的是文件内容,但现有代码直接对
os.listdir返回的文件名做正则匹配,完全不符合需求。 - 路径错误:
os.listdir仅返回目录下的文件名,读取文件时需要拼接完整路径,否则会找不到文件。 - 业务逻辑缺失:没有实现“仅匹配pattern2不匹配pattern1直接忽略”的要求。
修复后的完整代码
import re import os # 预编译正则 pattern1 = re.compile(r'critical', re.IGNORECASE) pattern2 = re.compile(r'gouting bile', re.IGNORECASE) dir_path = '/home/ea/medical' for filename in os.listdir(dir_path): file_full_path = os.path.join(dir_path, filename) # 跳过子目录,只处理文件 if not os.path.isfile(file_full_path): continue # 读取文件内容,编码可根据实际文本调整 try: with open(file_full_path, 'r', encoding='utf-8') as f: content = f.read() except: # 读取失败的文件可按需处理,这里直接跳过 continue # 匹配判断 match1 = pattern1.search(content) is not None match2 = pattern2.search(content) is not None if match1 and match2: status = 3 print(filename, "Status: ", status) elif match1 and not match2: status = 2 print(filename, "Status: ", status) elif not match1 and not match2: status = 1 print(filename, "Status: ", status) # 仅匹配pattern2的情况直接忽略,不做处理
额外运行检查项
- 确认
/home/ea/medical目录存在,且当前运行用户有该目录的读取权限 - 确认目录下的文本文件编码与
open语句中指定的编码一致,若读取乱码可尝试将encoding='utf-8'修改为encoding='gbk'或者添加errors='ignore'参数忽略编码错误。
内容的提问来源于stack exchange,提问作者EA Bubnoff
相关产品推荐
相关产品推荐

