Python中的频率分析程序

我是python编程的新手。现在在程序的一部分中,我想为频率分析定义一个类,并以漂亮的样式打印它:

Letter    Occurrence    Percentage
  a          12            4.12%
  b          7             3.15%
  c          21            7.67%
 ...        ...             ...

这是我的代码:

class Analysis():

    def __init__(self, sentence, freq_dict = {}):
        self.sentence = sentence
        self.freq_dict = freq_dict

    @property
    def frequency(self):
        print("\t\tLetter\t\tOccurrence\t\tPrecentage")
        for letter, occurrence in enumerate(self.freq_dict):
            return f"\t\t{letter}\t\t{occurrence}\t\t{round(occurrence*100/len(sentence), 2)}%"

    @frequency.setter
    def frequency(self, sentence):
        self.sentence = sentence
        for letter in sentence:
            freq_dict[letter] = self.sentence.count(letter)
        return freq_dict


sentence = input("please enter your sentence: ").lower()
object = Analysis(sentence)
print(object.frequency())

1- i want to use @propery decorador for get and set values in class.

2-我想在类的setter函数中定义句子的输入,而不是全局变量。

我找不到一种使用类和@property的方法,它有一些问题。可能会更短或更改一些行。 (代替字典,也许我可以使用collections.Counter(sentence),它返回一个元组)。

评论