萬盛學電腦網

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

Python 字串分割與英文單詞統計:split、正則與計數器完整教學

字串分割基礎:str.split()

基本用法


# 指定分隔符
text = "a|and|hello|||ab"
parts = text.split('|')
print(parts)
# ['a', 'and', 'hello', '', '', 'ab']  # 連續分隔符產生空字串

# 預設分隔符:任意空白字元 (空格、Tab、換行),自動合併連續空白、去除首尾
text = "a  hello   world\t\npython"
parts = text.split()
print(parts)
# ['a', 'hello', 'world', 'python']  # 無空字串

限制分割次數


text = "a,b,c,d,e"
print(text.split(',', 2))   # ['a', 'b', 'c,d,e']  最多分割 2 次
print(text.rsplit(',', 2))  # ['a,b,c', 'd', 'e']  從右側開始分割

進階分割:re.split() 正則表達式


import re

# 多種分隔符
text = "apple,banana;orange|grape"
parts = re.split(r'[,\;\|]', text)
# ['apple', 'banana', 'orange', 'grape']

# 保留分隔符
parts = re.split(r'([,\;\|])', text)
# ['apple', ',', 'banana', ';', 'orange', '|', 'grape']

# 以一或多個空白分割 (同 str.split() 行為)
parts = re.split(r'\s+', "a  b\tc\n d")
# ['a', 'b', 'c', 'd']

英文單詞統計三種方案

方案一:基礎版 (原文改良)


import sys
import string
from collections import Counter

def count_words_basic(filenames):
    """統計檔案中單詞出現次數 (忽略標點、數字、大小寫)"""
    # 定義要移除的字元:空白、標點、數字、引號
    strip_chars = string.whitespace + string.punctuation + string.digits + "\"'"
    
    counter = Counter()
    
    for filename in filenames:
        try:
            with open(filename, 'r', encoding='utf-8') as f:
                for line in f:
                    for word in line.split():
                        # 移除首尾非字母字元
                        clean = word.strip(strip_chars).lower()
                        if len(clean) >= 2:  # 過濾太短詞
                            counter[clean] += 1
        except OSError as e:
            print(f"讀取 {filename} 失敗: {e}", file=sys.stderr)
    
    return counter

if __name__ == '__main__':
    if len(sys.argv) < 2:
        print("用法: python wordcount.py file1.txt [file2.txt ...]")
        sys.exit(1)
    
    counts = count_words_basic(sys.argv[1:])
    for word, count in counts.most_common():
        print(f"'{word}' occurs {count} times")

方案二:正則版 (更精確的單詞邊界)


import re
from collections import Counter

WORD_PATTERN = re.compile(r"\b[a-zA-Z']+\b")  # 單詞邊界:字母與撇號

def count_words_regex(filenames):
    counter = Counter()
    for filename in filenames:
        try:
            with open(filename, 'r', encoding='utf-8') as f:
                text = f.read().lower()
                words = WORD_PATTERN.findall(text)
                counter.update(words)
        except OSError as e:
            print(f"讀取失敗: {e}", file=sys.stderr)
    return counter

方案三:生產級 (大檔案流式處理、記憶體友善)


import re
import sys
from collections import Counter

WORD_RE = re.compile(r"[a-z']+", re.IGNORECASE)

def count_words_streaming(filenames, top_n=20):
    counter = Counter()
    for filename in filenames:
        try:
            with open(filename, 'r', encoding='utf-8', errors='ignore') as f:
                for line in f:
                    words = WORD_RE.findall(line.lower())
                    counter.update(words)
        except OSError as e:
            print(f"錯誤: {e}", file=sys.stderr)
    
    # 輸出前 N 高頻詞
    for word, count in counter.most_common(top_n):
        print(f"{word:<15} {count:>8}")

if __name__ == '__main__':
    count_words_streaming(sys.argv[1:])

效能與記憶體比較

方案記憶體速度準確度適用場景
基礎 split + strip低 (逐行)中中 (標點處理粗略)小檔案、教學
正則 findall中 (整檔讀入)快 (C 實作)高 (邊界精確)中等檔案
流式 + 正則極低 (逐行)快高大檔案、GB 級
CounterO(唯一詞數)C 優化精確所有場景推薦

常見陷阱

  • 編碼錯誤:指定 encoding='utf-8',加 errors='ignore' 或 'replace' 容錯
  • 大小寫:統一 .lower() 或 .casefold() (Unicode 更完整)
  • 縮寫與連字號:don't、mother-in-law 需決定是否拆分,調整正則
  • Unicode 字母:\w 包含底線和數字,[a-zA-Z] 只含 ASCII,多語言用 \p{L} (需 regex 模組)

總結

Python 字串分割與單詞統計,核心工具是 str.split()、re.split()/findall()、collections.Counter。根據檔案大小、準確度需求、記憶體限制選擇適當方案。生產環境推薦流式讀取 + 正則 + Counter組合,兼顧效能、記憶體與準確度。

copyright © 萬盛學電腦網 all rights reserved