You need to enable JavaScript to run this app. Python统计输入字符串负面关键词时触发AttributeError报错咨询
优惠活动
大模型
产品
解决方案
定价
更多

Python统计输入字符串负面关键词时触发AttributeError报错咨询

代码问题定位与修复

核心问题列表

  • 缩进层级错误:接收用户输入、字符串拆分、负面词计数的逻辑全部被错误嵌套在外层遍历负面词的循环内,程序会每展示一个负面词就弹出一次输入框,不符合预期流程。
  • 触发报错的直接原因:判断条件if word in i.my_string.split()中,i是用户输入拆分后的普通字符串元素,不存在my_string属性,直接触发AttributeError;且该行重复执行split()的逻辑完全冗余。
  • 变量引用错位:内层计数循环遍历用户输入词汇时,判断条件错用了外层负面词循环的临时变量,无法完成正确匹配。
  • 类型拼接错误:最终打印结果时,直接将整数类型的计数值与字符串拼接,会触发类型不匹配异常。

修复后可运行代码

# neg_words为预先定义的负面词汇列表
for word in neg_words:
    if word != neg_words[-1]:
        print(f"'{word}',", end=' ')
    else:
        print(f"and '{word}.'")
print()

# 输入处理、计数逻辑移出外层循环,独立执行
my_string = input("Type here without quotes what the customer said: ")
split_up_my_string = my_string.split()
negative = 0

# 遍历拆分后的输入词汇,匹配负面词完成计数
for input_word in split_up_my_string:
    # 兼容大小写匹配,避免因格式差异漏计
    if input_word.lower() in [w.lower() for w in neg_words]:
        negative += 1

print()
# 计数值转换为字符串后再拼接输出
print("This consumer mentioned negative keywords a total of " + str(negative) + " times.")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.25 02:54:03