Сортированный словарь возвращает NoneType вместо списка? - PullRequest
0 голосов
/ 21 апреля 2019

Итак, я пытаюсь написать программу для чтения в текстовом файле, затем удалить стоп-слова, затем найти наиболее распространенные слова и записать их в словарь, а затем отсортировать словарь.

Кажется, что я в состоянии найти самые обычные слова просто отлично, но когда я сортирую словарь, чтобы сначала отобразить большинство найденных слов, вместо списка возвращается NoneType, и я получаю 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".

Ответы [ 2 ]

2 голосов
/ 21 апреля 2019

lst.reverse является изменяемой операцией и возвращает None, вам не следует повторно оценивать переменную:

e = sorted(word_count.items(), key=lambda item: item[1])
e.reverse()
e[:4]
0 голосов
/ 21 апреля 2019

Надеюсь, это поможет! включить обратное = True в сам отсортированный метод

from string import punctuation
from collections import Counter

with open('Sense_and_Sensibility.txt','r') as f:
    sense_and_sensibility_dirty = f.read()

with open('stopwords.txt','r') as f:
    stopwords = f.read().split()
stop_words = [x.lower() for x in stop_words]

sense_and_sensibility_dirty = sense_and_sensibility_dirty.lower()
all_text = ''.join([c for c in sense_and_sensibility_dirty if c not in punctuation])

sense_and_sensibility_dirty_split = all_text.split('\n')
all_text = ' '.join(sense_and_sensibility_dirty_split)
words = all_text.split()
req_words = [word for word in words if word not in stop_words]

word_counts = Counter(req_words)
sorted_words = sorted(word_counts, key = word_counts.get, reverse= True)
...