繁体   English   中英

它什么也没给。 有人可以帮助我了解 python 中的字典、对象和类吗?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM