萬盛學電腦網

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

Python 統計檔案字數:逐行讀取、分詞計數完整範例

核心邏輯

  1. 開啟檔案
  2. 逐行讀取 (避免大檔吃光記憶體)
  3. 分詞 (預設按空白字元)
  4. 累加計數

基本實作


def count_words(text):
    return len(text.split())

def count_file_words(filename):
    total = 0
    with open(filename, 'r', encoding='utf-8') as f:
        for line in f:
            total += count_words(line)
    return total

print(count_file_words('welcome.txt'))

進階:支援中文分詞

英文以空白分詞,中文需斷詞庫:


# jieba 範例
import jieba
def count_chinese_words(text):
    return len(list(jieba.cut(text)))

大檔案優化:readlines(sizehint)


def count_large_file(filename, chunk_size=200*1024*1024):  # 200MB
    total = 0
    with open(filename, 'r', encoding='utf-8') as f:
        while True:
            lines = f.readlines(chunk_size)
            if not lines:
                break
            for line in lines:
                total += len(line.split())
    return total

readlines(sizehint) 回傳約略大小的完整行列表,平衡記憶體與效能。

檔案物件屬性速查

屬性/方法說明
closed是否已關閉
encoding檔案編碼
mode開啟模式
name檔名
newlines遇到的換行符元組
read(size)讀指定位元組
readline()讀一行
readlines(sizehint)讀多行列表
write(str)寫入字串
writelines(seq)寫入字串序列
seek(offset, whence)移動指標
tell()目前指標位置
truncate(size)截斷檔案

最佳實務

  • 永遠使用 with open(...) as f: 確保關閉
  • 明確指定 encoding (建議 UTF-8)
  • 大檔逐行或分塊處理
  • 中文文本請用專業斷詞庫
copyright © 萬盛學電腦網 all rights reserved