如何解决它不给任何东西有人可以帮助我了解 Python 中的字典、对象和类吗?
我正在尝试打印文本中所有单词的频率。 我想根据它们的排序值打印所有键。 也就是说,我想打印从最频繁到最不频繁的频率。 这是我的代码:
freqMap = {}
class analysedText(object):
def __init__(self,text):
# remove punctuation
formattedText = text.replace('.','').replace('!','').replace('?','').replace(',','')
# make text lowercase
formattedText = formattedText.lower()
self.fmtText = formattedText
def freqAll(self):
wordList = self.fmtText.split(' ')
freqMap = {}
for word in set(wordList):
freqMap[word] = wordList.count(word)
return freqMap
mytexte = str(input())
my_text = analysedText(mytexte)
my_text.freqAll()
freqKeys = freqMap.keys()
freqValues = sorted(freqMap.values())
a = 0
for i in freqValues:
if i == a:
pass
else:
for key in freqKeys:
if freqMap[key] == freqValues[i]:
print(key,": ",freqValues[i])
a = i
解决方法
您的函数 freqAll
返回一个您没有捕捉到的值。
应该是:
counts = my_text.freqAll()
然后在其余代码中使用 counts 变量。
,freqAll
你的类的方法做了 return
freqMap
你应该存储但不要这样做,因此你实际上正在处理创建的空字典 freqMap
在类声明之前。尝试更换
my_text.freqAll()
使用
freqMap = my_text.freqAll()