[英]It doesn't give anthing. Can someone help me about dictionaries and objects and classes in 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
您的 function freqAll
返回一個您沒有捕捉到的值。 它應該是:
counts = my_text.freqAll()
然后在代碼的 rest 中使用 counts 變量。
您的 class 的freqAll
方法確實return
您應該存儲但不這樣做的freqMap
,因此您實際上正在處理空字典freqMap
,它是在 class 聲明之前創建的。 嘗試更換
my_text.freqAll()
使用
freqMap = my_text.freqAll()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.