採用流式處理 (逐行讀取) 避免大檔案記憶體溢位,並同步統計四項指標:總行數、空白行數、句子數、單字數。
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 (行數) 極速但平台相依。