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

第二个Python函数触发UnboundLocalError,第一个函数运行正常

解决UnboundLocalError:local variable 'data_list' referenced before assignment

错误根源

  1. data_list未提前初始化:原代码中data_list = data.split()仅在if c in data分支执行,若输入data不含指定标点(?、●等),该分支不会触发,data_list从未被定义,后续引用时直接报错。
  2. 缩进错误:原函数中处理停用词的代码块未缩进在def words_list(data):函数体内,导致这部分逻辑不属于函数,执行顺序完全错误。
  3. 标点替换逻辑冗余:原代码先判断字符是否存在再替换,可直接循环完成所有标点替换,无需额外判断。

修正后的代码

import os

def words_list(data):
    # 提前初始化data_list,避免未定义情况
    data_list = data.split()
    
    # 统一替换所有指定标点,无需判断是否存在
    for c in ['?','●','.',',','|','>','<','(',')']:
        data = data.replace(c, '')
    # 替换后重新拆分数据
    data_list = data.split()
    
    # 处理停用词(确保缩进在函数内部)
    path = 'C:\\Users\\p12m9\\Documents\\Python Coding\\Data Science Projects\\Job Assignment\\Job 2 (Web Crawling)\\StopWords'
    os.chdir(path)
    
    # 收集所有停用词到集合(查询效率更高)
    all_stop_words = set()
    for files in os.listdir():
        if files.endswith(".txt"):
            file_path = f"{path}\\{files}"
            with open(file_path, 'r') as f:
                stop_words = f.read().split()
                # 过滤停用词中的标点
                cleaned_stop_words = [word for word in stop_words if word not in ['?','●','.',',','|','>','<','(',')']]
                all_stop_words.update(cleaned_stop_words)
    
    # 统一转小写后过滤停用词,避免重复转换
    data_list = [word.lower() for word in data_list]
    data_list = [word for word in data_list if word not in all_stop_words]
    
    return data_list

关键改动说明

  • 提前初始化变量:无论输入数据是否含标点,都保证data_list已定义,彻底解决未绑定变量错误。
  • 修正缩进问题:将所有逻辑缩进在函数内部,确保代码执行顺序符合预期。
  • 优化停用词处理:将所有停用词存入集合(集合查询时间复杂度为O(1)),避免重复打开文件和重复转换大小写,提升效率。
  • 简化标点替换:直接循环替换所有目标标点,逻辑更简洁高效。

额外优化建议

  • 读取停用词文件时,建议按行读取并过滤空行:stop_words = [line.strip() for line in f if line.strip()],避免读取无效内容。
  • 路径拼接使用os.path.join()替代手动拼接:file_path = os.path.join(path, files),避免因系统路径分隔符差异导致的错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 09:25:28