python - 排序字典返回 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".
解决方案
lst.reverse
是一个可变操作并返回None
,你不应该重新评估变量:
e = sorted(word_count.items(), key=lambda item: item[1])
e.reverse()
e[:4]
推荐阅读
- extjs - Ext JS 网格中的骨架加载
- javascript - 如何根据我的回复的行和列显示和禁用复选框?
- java - 无法在 android studio 中解析符号“coordinatorlayout”
- go - 将参数传递给 Echo 路由中间件
- c# - 绑定到内容控件中子控件的 DependencyProperty
- php - 显示来自mysql数据库的数据时面临问题
- java - 如何在 Android SDK API Level 29 或更高版本中获取 IMSI 编号?
- matlab - 如何获得一组耦合的 4 阶 odes 和代数方程的解
- python - 如何从 tfs 中提取链接到 python 中工作项的变更集?
- php - 在 Laravel 中调用 int 上的成员函数 count()?