简体   繁体   中英

It doesn't give anthing. Can someone help me about dictionaries and objects and classes in python?

I am trying to print frequencies of all words in a text. I wanna print all keys according to their sorted values. Namely, I wanna print the frequencies from most frequent to least frequent. Here is my code:

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

Your function freqAll returns a value that you are not catching. It should be:

counts = my_text.freqAll()

Then you use the counts variable in the rest of your code.

freqAll method of your class does return freqMap which you should store but do not do that, therefore you are in fact processing empty dict freqMap , which was created before class declaration. Try replacing

my_text.freqAll()

using

freqMap = my_text.freqAll()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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