'''
模板方法模式 (Template Method Pattern)

适用场景：定义词频统计的整体流程骨架，允许子类自定义某些步骤（如分词或输出格式）。

如何应用：
定义一个抽象类 WordFrequencyAnalyzer，包含固定的流程：读取文件 -> 分词 -> 统计 -> 输出。
具体步骤（如分词或输出）由子类实现。

优点：保证流程一致，子类只关注具体实现。

知识点：  
理解解继承与抽象类的使用。
如何定义固定流程，允许子类灵活实现。强调流程与实现的分离。
'''

from abc import ABC, abstractmethod
from typing import List, Dict
from collections import Counter

class WordFrequencyAnalyzer(ABC):
    def analyze(self, directory: str, top_n: int = 10):
        texts = self.read_texts(directory)
        word_counts = self.count_words(texts)
        self.print_results(word_counts, top_n)

    @abstractmethod
    def read_texts(self, directory: str) -> List[str]:
        pass

    @abstractmethod
    def count_words(self, texts: List[str]) -> Dict[str, int]:
        pass

    @abstractmethod
    def print_results(self, word_counts: Dict[str, int], top_n: int):
        pass

class SimpleAnalyzer(WordFrequencyAnalyzer):
    def read_texts(self, directory: str) -> List[str]:
        import os
        texts = []
        for filename in os.listdir(directory):
            if filename.endswith(".txt"):
                with open(os.path.join(directory, filename), "r", encoding="utf-8") as f:
                    texts.append(f.read())
        return texts

    def count_words(self, texts: List[str]) -> Dict[str, int]:
        import jieba
        word_counts = Counter()
        for text in texts:
            words = jieba.cut(text)
            word_counts.update([word for word in words if word.strip()])
        return dict(word_counts)

    def print_results(self, word_counts: Dict[str, int], top_n: int):
        top_words = sorted(word_counts.items(), key=lambda x: x[1], reverse=True)[:top_n]
        for word, count in top_words:
            print(f"{word}: {count}")

# 使用
analyzer = SimpleAnalyzer()
analyzer.analyze("data", 10)