You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ATBS Regex Search项目如何解决局部作用域UnboundLocalError错误?

问题修复方案

核心错误点

  • 作用域错误:FileList、RegexCompile等变量定义在Input_Folder函数内部,函数外的循环逻辑无法访问,同时Result_txt只有在if判断命中时才会赋值,没命中的场景下就会出现未定义报错
  • 语法逻辑错误:if file.endswith('.txt') in FileList 属于无效判断,endswith返回布尔值,无需再判断是否在文件列表中
  • 路径拼接错误:os.listdir(file) 传入的是纯文件名,没有拼接根目录路径,程序无法定位到实际文件位置
  • 缩进错误:with open 块下的代码没有正确缩进,会触发语法报错
  • 功能匹配错误:需求要求打印匹配正则的行,原代码只统计是否存在匹配,没有输出对应行内容

修正后代码

import os, re

def regex_search():
    # 接收用户输入
    search_folder = input('Please provide a folder path:')
    # 校验路径是否存在
    if not os.path.isdir(search_folder):
        print("输入的文件夹路径不存在")
        return
    search_regex = input('Please provide a regex to search for:')
    try:
        regex_compile = re.compile(search_regex)
    except re.error:
        print("输入的正则表达式不合法")
        return

    total_match_count = 0
    # 遍历文件夹下所有文件
    for filename in os.listdir(search_folder):
        if filename.endswith('.txt'):
            # 拼接完整文件路径
            full_path = os.path.join(search_folder, filename)
            print(f"\n===== 正在扫描文件:{filename} =====")
            file_match_count = 0
            # 逐行读取匹配
            with open(full_path, 'r', encoding='utf-8', errors='ignore') as f:
                for line_num, line_content in enumerate(f, 1):
                    if regex_compile.search(line_content):
                        file_match_count += 1
                        total_match_count += 1
                        print(f"第{line_num}行匹配:{line_content.strip()}")
            if file_match_count == 0:
                print("当前文件未找到匹配内容")
    
    print(f"\n扫描完成,所有文件共找到{total_match_count}处匹配")

if __name__ == "__main__":
    regex_search()

使用说明

  • 输入文件夹路径时可直接粘贴绝对路径,比如你测试用的/Users/myname/Documents/可直接输入
  • 正则输入符合Python re模块规范即可,比如要找包含hello的行直接输入hello,要找数字输入\d+

内容的提问来源于stack exchange,提问作者Newb2CodingCareer

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 06:24:02