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

Python基础情感分析代码预期返回匹配词 实际输出空列表问题排查

情感分析代码问题修复

问题根源

  • 函数参数硬编码:sentiment1函数内部调用预处理函数时直接传入了全局变量comment_1,没有使用传入的参数,函数复用性缺失。
  • 循环逻辑完全错误:判断条件将拆分后的单词列表的第一个元素和整个积极词列表做相等判断,字符串和列表数据类型不匹配,条件永远不成立,所以最终返回空列表。
  • 变量名冲突:循环变量名和积极词表变量名拼写接近,极易混淆逻辑。
  • 列表追加逻辑错误:匹配成功时追加的是整个拆分后的单词列表,不是匹配到的单个单词。

修复后代码

def remove_punc_and_split(wordlist): 
    punc = '.!?/:;,{}'  # 待移除的标点符号
    no_punc = "" 
    for char in wordlist:
        if char not in punc:
            no_punc = no_punc + char.lower()
    new_word_list = no_punc.split() # 将文本拆分为独立单词组成的列表
    return new_word_list

def sentiment1(input_text):
    positive_words = ["good","awesome","excellent","great"]
    # 使用传入的输入文本做预处理
    processed_words = remove_punc_and_split(input_text)
    pos_word_list = []                                                               
    # 遍历所有预处理后的单词
    for word in processed_words:
        # 判断当前单词是否属于积极词表
        if word in positive_words:
            pos_word_list.append(word)
            print(word)
    return pos_word_list
    
comment_1 = 'Good for the price, but poor Bluetooth connections.'
result = sentiment1(comment_1)
print("匹配到的积极词:", result)

运行结果

good
匹配到的积极词: ['good']

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 12:15:04