调用词频统计函数后访问字典值遇'NoneType'下标错误的解决方法
解决'NoneType' object is not subscriptable错误
你的代码报错的核心原因是count_words函数没有返回值——Python中函数如果没有显式写return语句,默认会返回None。所以执行cnt = count_words(my_words)后,cnt是None,你尝试用cnt['just']访问下标自然会触发错误。
修改方法
在count_words函数末尾添加return cnt_dict,把统计好的字典返回出来:
def count_words(word_list): "Count word frequencies of words in a list." cnt_dict = dict() for word in word_list: if word in cnt_dict: cnt_dict[word] += 1 else: cnt_dict[word] = 1 print(cnt_dict) return cnt_dict # 添加返回语句 my_words = ['this', 'is', 'just', 'a', 'test', 'example', 'to', 'test', 'some', 'example', 'code'] cnt = count_words(my_words) print(cnt['just']) # 现在可以正常获取值,输出1
额外优化(可选)
如果不想自己写循环统计词频,可以用Python标准库collections.Counter来简化代码,效果完全一致:
from collections import Counter my_words = ['this', 'is', 'just', 'a', 'test', 'example', 'to', 'test', 'some', 'example', 'code'] cnt = Counter(my_words) print(cnt['just']) # 输出1
内容的提问来源于stack exchange,提问作者Thomas
相关产品推荐
相关产品推荐

