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)