You need to enable JavaScript to run this app. Python实现多文件夹下review.txt跨文件重复行查找的高效方案咨询
优惠活动
大模型
产品
解决方案
定价
更多

Python实现多文件夹下review.txt跨文件重复行查找的高效方案咨询

多txt文件重复行比对实现指南

场景说明

  • 目录结构:指定根目录下嵌套多个子文件夹(如f1、f2、f3...),每个子文件夹中存在同名review.txt文本文件
  • 核心目标:匹配某一个文件中的任意一行文本,定位所有其他包含完全相同行内容的文件位置,替代当前多层嵌套循环的臃肿实现
  • 参考文本格式:txt内通常为带路径前缀的日志类内容,每行包含文件路径、行号、问题描述,例如:
    classes/CadenceMyProfileController1.cls:6:    Avoid really long classes (lines of code)
    /data/public/pmd/repo/src/1/src/classes/CadenceMyProfileController1.cls:6:    Missing ApexDoc comment
    

原有代码格式化

原实现存在缩进混乱、嵌套层级过深、重复打开文件的问题,格式化后的可运行结构如下:

import os

res = []
def find_error(content, prefix):
    # 原自定义文本清洗逻辑占位
    return content.strip()

for root, dirs, files in os.walk('root'):
    for file in files:
        if file != "review.txt":
            continue
        with open(os.path.join(root, file), "r") as auto:
            curr_file_path = os.path.join(root, file)
            curr_file_num = curr_file_path
            lines = auto.readlines()
            for line_num, line in enumerate(lines):
                curr_sent = find_error(line, f"{curr_file_num}:    ")
                # 逐行匹配时重复打开基准源文件
                with open("root/f1/review.txt", "r") as f:
                    src_lines = f.readlines()
                    for src_line_num, src_line in enumerate(src_lines):
                        src_sent = find_error(src_line, f"{src_line_num}:    ")
                        if src_sent == curr_sent:
                            res.append([line_num])

高效优化方案

优化思路

原有实现的性能瓶颈在于:每读取一行文本就重新打开一次基准文件逐行比对,整体时间复杂度为O(所有文件总行数的平方),文件量稍大就会出现明显卡顿。优化核心为一次性遍历全量文件建立反向索引,将平方级的比对操作转为线性遍历,查询时直接通过索引匹配结果。

实现代码

import os
from collections import defaultdict

def find_error(content, prefix=""):
    # 保留原有文本清洗逻辑,默认去除首尾空白、换行符
    return content.strip()

def build_line_index(root_path: str, target_filename: str = "review.txt"):
    # 反向索引:清洗后的文本行 -> 存储所有包含该行的文件路径
    line_to_files = defaultdict(list)
    # 缓存映射:文件全路径 -> 该文件下的所有原始行内容
    file_raw_lines = {}

    for dir_path, _, filenames in os.walk(root_path):
        if target_filename not in filenames:
            continue
        full_file_path = os.path.join(dir_path, target_filename)
        with open(full_file_path, "r", encoding="utf-8") as f:
            raw_lines = f.readlines()
            file_raw_lines[full_file_path] = raw_lines
            for line_content in raw_lines:
                cleaned_line = find_error(line_content)
                # 跳过空行,避免无效匹配
                if not cleaned_line:
                    continue
                # 同文件内多次出现相同行时,仅记录一次文件路径,避免结果重复
                if full_file_path not in line_to_files[cleaned_line]:
                    line_to_files[cleaned_line].append(full_file_path)
    return line_to_files, file_raw_lines

if __name__ == "__main__":
    # 替换为你的实际根目录路径
    target_root = "./你的根目录"
    line_index, file_content_cache = build_line_index(target_root)

    # 示例:查询f1/review.txt第一行的匹配结果
    target_file = os.path.join(target_root, "f1", "review.txt")
    if target_file not in file_content_cache:
        raise FileNotFoundError("未找到指定的基准文件")
    
    first_line = file_content_cache[target_file][0]
    cleaned_target = find_error(first_line)
    # 获取所有包含该行的文件
    matched_all = line_index.get(cleaned_target, [])
    # 过滤掉基准文件自身,仅保留其他匹配文件
    matched_other = [path for path in matched_all if path != target_file]

    print(f"目标行内容:{cleaned_target}")
    print(f"包含该行的其他文件列表:{matched_other}")

方案优势

  • 性能提升:全量遍历仅执行一次,建立索引后匹配查询为常数级操作,相比原嵌套循环逻辑,文件量越大性能优势越明显
  • 结构清晰:将文件读取、索引构建、结果查询拆分为独立模块,无多层嵌套循环,后续新增过滤规则(如排除指定目录、修改匹配精度)时无需改动核心遍历逻辑
  • 细节适配:自动跳过空行、自动去重同文件内的重复路径记录,不会出现结果列表冗余

内容的提问来源于stack exchange,提问作者Vaibhav kumar Chaudhary

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.12.04 05:54:02