批量搜索TXT文件分类后,如何输出无匹配短语的文件路径?
筛选未匹配指定短语的文件路径
你的代码逻辑出错是因为字符串的逻辑或运算特性——非空字符串在布尔判断里都是True,所以('word1') or ('word2') or ('word3')会直接返回第一个非空字符串'word1',导致代码实际只检查'word1'是否不在文件内容里,完全忽略了word2和word3的判断。
修正后的完整代码(含分类判断+未匹配筛选)
# 遍历存储文件路径的列表FList for file_path in FList: with open(file_path, 'r', encoding='utf-8') as txtfile: content = txtfile.read() # 按匹配规则归类输出 if 'word1' in content: print(f"{file_path}: Category I") elif 'word2' in content: print(f"{file_path}: Category II") elif 'word3' in content: print(f"{file_path}: Category III") # 未匹配任何短语时输出文件路径 else: print(f"未匹配任何短语: {file_path}")
单独筛选未匹配文件的简洁写法
如果只需要输出未匹配的文件路径,可以用any()函数简化判断:
target_phrases = ['word1', 'word2', 'word3'] for file_path in FList: with open(file_path, 'r', encoding='utf-8') as txtfile: content = txtfile.read() # 检查是否所有短语都不在文件内容中 if not any(phrase in content for phrase in target_phrases): print(file_path)
内容的提问来源于stack exchange,提问作者WhiteWolf1965
相关产品推荐
相关产品推荐

