【问题标题】:It doesn't give anthing. Can someone help me about dictionaries and objects and classes in python?它什么也没给。有人可以帮我了解python中的字典、对象和类吗?
【发布时间】:2021-06-16 21:27:39
【问题描述】:

我正在尝试打印文本中所有单词的频率。 我想根据它们的排序值打印所有键。 也就是说,我想打印从最频繁到最不频繁的频率。 这是我的代码:

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

【问题讨论】:

    标签: python list class dictionary error-handling


    【解决方案1】:

    您的函数freqAll 返回一个您没有捕捉到的值。 应该是:

    counts = my_text.freqAll()
    

    然后在其余代码中使用 counts 变量。

    【讨论】:

      【解决方案2】:

      你的类的freqAll 方法执行return freqMap 你应该存储但不要这样做,因此你实际上是在处理空字典freqMap,它是在类声明之前创建的。换个试试

      my_text.freqAll()
      

      使用

      freqMap = my_text.freqAll()
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-11-03
        • 1970-01-01
        • 1970-01-01
        • 2020-12-24
        • 2022-06-16
        • 2016-01-24
        相关资源
        最近更新 更多