如何统计文本中指定形容词的数量?排查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())
修正说明
- 提前初始化计数器:基于形容词列表创建初始值为0的
Counter,避免循环内重复重置统计结果 - 文本预处理:去除标点、统一转为小写,确保"bad,"、"Good"这类变体都能被正确识别
- 实现计数逻辑:遍历每个文本的单词,匹配到目标形容词时更新计数
运行修正后的代码,就能得到你预期的输出结果。
内容的提问来源于stack exchange,提问作者GlitzerImHirn
相关产品推荐
相关产品推荐

