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