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.
102 lines
2.9 KiB
102 lines
2.9 KiB
from collections import Counter
|
|
from cppy.cp_util import *
|
|
|
|
|
|
class DataStorageManager:
|
|
"""
|
|
数据模型,读取文件内容,并将内容分割成单词。
|
|
|
|
Attributes:
|
|
_data: 单词列表。
|
|
|
|
Methods:
|
|
_words (self): 返回分割后的单词列表。
|
|
"""
|
|
|
|
def __init__(self, path_to_file):
|
|
self._data = re_split(read_file(path_to_file))
|
|
|
|
def words(self):
|
|
"""返回分割后的单词列表。"""
|
|
return self._data
|
|
|
|
|
|
class StopWordManager:
|
|
"""
|
|
停用词模型
|
|
|
|
Attributes:
|
|
_stop_words: 停用词列表
|
|
|
|
Methods:
|
|
is_stop_word (self, word): 判断给定单词是否为停用词。
|
|
"""
|
|
|
|
def __init__(self):
|
|
self._stop_words = get_stopwords()
|
|
|
|
def is_stop_word(self, word):
|
|
"""判断给定单词是否为停用词。"""
|
|
return word in self._stop_words
|
|
|
|
|
|
class WordFrequencyManager:
|
|
"""
|
|
词频模型,计算并管理单词的频率。
|
|
|
|
Attributes:
|
|
_word_freqs: 使用 Counter 存储单词及其出现次数。
|
|
|
|
Methods:
|
|
increment_count (self, word): 计算词频。
|
|
sorted(self): 返回按出现次数排序的单词列表。
|
|
|
|
"""
|
|
|
|
def __init__(self):
|
|
self._word_freqs = Counter()
|
|
|
|
def increment_count(self, word):
|
|
"""计算词频。"""
|
|
self._word_freqs[word] += 1
|
|
|
|
def sorted(self):
|
|
"""返回按出现次数排序的单词列表。"""
|
|
return self._word_freqs.most_common()
|
|
|
|
|
|
class WordFrequencyController:
|
|
"""
|
|
控制器,控制整个流程,读取文件、处理停用词、计算词频并输出结果。
|
|
|
|
Attributes:
|
|
_storage_manager: DataStorageManager 实例,用于读取和处理文件内容。
|
|
_stop_word_manager: StopWordManager 实例,用于管理停用词。
|
|
_word_freq_manager: WordFrequencyManager 实例,用于计算和存储单词频率。
|
|
|
|
Methods:
|
|
run(self): 运行方法,遍历单词列表,过滤掉停用词,并计算每个单词的频率,最后输出结果。
|
|
"""
|
|
|
|
def __init__(self, path_to_file):
|
|
self._storage_manager = DataStorageManager(path_to_file)
|
|
self._stop_word_manager = StopWordManager()
|
|
self._word_freq_manager = WordFrequencyManager()
|
|
|
|
def run(self):
|
|
"""运行方法,遍历单词列表,过滤掉停用词,并计算每个单词的频率,最后输出结果。"""
|
|
for w in self._storage_manager.words():
|
|
if not self._stop_word_manager.is_stop_word(w):
|
|
self._word_freq_manager.increment_count(w)
|
|
|
|
word_freqs = self._word_freq_manager.sorted()
|
|
print_word_freqs(word_freqs)
|
|
|
|
|
|
if __name__ == '__main__':
|
|
WordFrequencyController(testfilepath).run()
|
|
'''
|
|
函数输入参数调用后,你的马上接住返回值
|
|
类输入参数后实例化后,你可以需要的时候去访问你需要的数据(实例属性)
|
|
'''
|