首页 > 解决方案 > 排序字典返回 NoneType 而不是列表?

问题描述

所以,我正在尝试编写一个程序来读取文本文件,然后删除停用词,然后找到最常用的单词并将它们写入字典,然后对字典进行排序。

似乎我能够很好地找到最常用的单词,但是当我对字典进行排序以首先显示找到的最多的单词时,返回 NoneType 而不是 list 并且我得到一个 TypeError。这是为什么?

import string

#Read in book and stopwords (lower case)
sense_and_sensibility_dirty = open("Sense_and_Sensibility.txt").read().rstrip("\n")
stop_words = open("stopwords.txt").read().split()
stop_words = [x.lower() for x in stop_words]

#Remove punctuation from the book and clean it up
translator = str.maketrans('', '', string.punctuation)
sns = sense_and_sensibility_dirty.translate(translator)
sns = sns.split()

#Convert words in book to lowercase
sns = [x.lower() for x in sns]
#Remove stop words from book
sns = [x for x in sns if x not in stop_words]

#Count up words in the book and write word and count to dictionary
word_count={}
for word in sns:
    if word not in word_count:
        word_count[word] = 1
    else:
        word_count[word] += 1

#Sort the dictionary to display most frequent
e = sorted(word_count.items(), key=lambda item: item[1])
e = e.reverse()
e[:4]

例如, e[:4] 应该输出如下内容:

[('time', 237), ('dashwood', 224), ('sister', 213), ('miss', 209)]

但相反,我得到:

"TypeError: 'NoneType' object is not subscriptable".

标签: pythondictionarynonetype

解决方案


lst.reverse是一个可变操作并返回None,你不应该重新评估变量:

e = sorted(word_count.items(), key=lambda item: item[1])
e.reverse()
e[:4]

推荐阅读