萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Python 統計文本檔案行數、句子與單字數完整實作

核心邏輯:逐行讀取與計數器更新

採用流式處理 (逐行讀取) 避免大檔案記憶體溢位,並同步統計四項指標:總行數、空白行數、句子數、單字數。

現代化 Python 3 實作 (含型別提示)

import sys
from pathlib import Path

def analyze_text_file(filepath: str, encoding: str = 'utf-8') -> dict:
    """統計檔案行數、空白行、句子數、單字數"""
    counters = {'lines': 0, 'blank_lines': 0, 'sentences': 0, 'words': 0}
    
    try:
        with open(filepath, 'r', encoding=encoding) as f:
            for line in f:
                counters['lines'] += 1
                
                # 空白行判斷:strip 後為空
                if not line.strip():
                    counters['blank_lines'] += 1
                    continue
                
                # 句子數:以 . ! ? 結尾計數 (簡易啟發式)
                counters['sentences'] += line.count('.') + line.count('!') + line.count('?')
                
                # 單字數:split() 預設按任意空白分割,自動處理多重空格
                words = line.split()
                counters['words'] += len(words)
                
    except FileNotFoundError:
        print(f"錯誤: 找不到檔案 {filepath}", file=sys.stderr)
        sys.exit(1)
    except UnicodeDecodeError:
        print(f"錯誤: 編碼 {encoding} 讀取失敗,嘗試其他編碼", file=sys.stderr)
        sys.exit(1)
        
    return counters

if __name__ == "__main__":
    # 範例:分析葛底斯堡演說
    target = Path(__file__).with_name("GettysburgAddress.txt")
    result = analyze_text_file(str(target))
    
    print("-" * 50)
    print(f"總行數      : {result['lines']}")
    print(f"空白行數    : {result['blank_lines']}")
    print(f"句子數 (估): {result['sentences']}")
    print(f"單字數      : {result['words']}")
    print("-" * 50)

關鍵技術細節

指標計算方式備註
行數每次迴圈 += 1含空白行
空白行not line.strip()純空白/Tab/換行視為空白
句子數count('.')+count('!')+count('?')簡易啟發式,無法處理縮寫 (Mr.)、省略號... 等
單字數len(line.split())split() 無參數 = 任意長度空白分割,符合詞彙定義

進階改良:更精確的句子分割


import re

# 使用正則避開常見縮寫 (簡易版)
SENTENCE_END = re.compile(r'(? int:
    return len(SENTENCE_END.findall(text))

大檔案效能建議

  • 使用 mmap (memory-mapped file) 配合正則掃描,避免 Python 層級迴圈開銷。
  • 或呼叫系統工具:wc -w (單字)、wc -l (行數) 極速但平台相依。
  • 並行處理:將檔案切分區塊,多進程統計後聚合 (需處理邊界單字/句子)。
copyright © 萬盛學電腦網 all rights reserved