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

如何统计文本中指定形容词的数量?排查Python代码错误

问题:统计形容词在文本中出现次数的代码错误分析

我有一组形容词,想要统计这些形容词在文本中的出现次数。以下是我当前使用的代码:

from collections import Counter

adjectives = ["good", "bad", "worst"] # 后续会替换为目标形容词列表

texts = ["This is not good", "The situation is bad, but not the worst", "How dare you, this is so good programmed! Very good!"]

for words in texts:
    counts = Counter(adjectives)
    
counts.items()

预期输出为:

dict_items([('good', 3), ('bad', 1), ('worst', 1)])

代码错误点

  • 计数器重复重置:你在for循环内部每次都重新创建counts = Counter(adjectives),这会彻底清空之前的统计结果。循环结束后,counts只是最后一次初始化的空计数器,完全没统计到文本内容。
  • 未执行计数逻辑:循环仅遍历了文本列表,但没有对文本中的单词做拆分、匹配和计数操作,等于做了无用循环。

修正后的代码

from collections import Counter
import string

adjectives = ["good", "bad", "worst"]  # 后续可替换为目标形容词列表
texts = ["This is not good", "The situation is bad, but not the worst", "How dare you, this is so good programmed! Very good!"]

# 基于形容词列表初始化计数器,初始计数为0
counts = Counter({adj: 0 for adj in adjectives})

for text in texts:
    # 清除文本标点并转为小写,避免标点、大小写干扰匹配
    cleaned_text = text.translate(str.maketrans('', '', string.punctuation)).lower()
    words = cleaned_text.split()
    # 遍历单词,匹配到目标形容词就累加计数
    for word in words:
        if word in counts:
            counts[word] += 1

print(counts.items())

修正说明

  1. 提前初始化计数器:基于形容词列表创建初始值为0的Counter,避免循环内重复重置统计结果
  2. 文本预处理:去除标点、统一转为小写,确保"bad,"、"Good"这类变体都能被正确识别
  3. 实现计数逻辑:遍历每个文本的单词,匹配到目标形容词时更新计数

运行修正后的代码,就能得到你预期的输出结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 20:12:45