You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

31 lines
711 B

8 months ago
from cppy.cp_util import *
from collections import Counter
8 months ago
# 定义一个带计数器的元类
class CounterMetaclass(type):
def __new__(mcs, name, bases, attrs):
attrs['_counter'] = Counter()
8 months ago
return super().__new__(mcs, name, bases, attrs)
8 months ago
# 基于元类创建类
class Word(metaclass=CounterMetaclass):
8 months ago
def __init__(self, word):
self.word = word
self._counter[self.word] += 1
@classmethod
def get_word_freqs(cls, n) -> Counter:
8 months ago
return cls._counter.most_common(n)
for word in extract_file_words(testfilepath):
Word(word)
print_word_freqs(Word.get_word_freqs(10))
8 months ago
'''
常用于将依赖项如服务或配置自动注入到类中
'''