萬盛學電腦網

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

Python 字串過濾:移除不在指定字元集合中的字元 (str.translate 高效實作)

需求

給定一組「允許字元」集合 (如僅保留母音 aeiouy),過濾字串中**不在集合內**的所有字元。

高效解法:str.translate + 查表

str.translate(table) 接受一個長度 65536 (Unicode BMP) 或字典的映射表,將字元碼點映射至新字元或 None (刪除)。**單次 C 層級遍歷,效能極佳。**


class CharFilter:
    """建立可重用的字元過濾器"""
    __slots__ = ('_table',)

    def __init__(self, keep_chars: str):
        # 允許字元集合 → 保留;其他映射為 None (刪除)
        keep_set = set(keep_chars)
        # 建立映射表:dict 形式更節省記憶體
        self._table = {cp: None for cp in range(0x10000) if chr(cp) not in keep_set}
        # BMP 之外字元 (Emoji 等) 預設保留;若需刪除請擴充邏輯

    def __call__(self, s: str) -> str:
        return s.translate(self._table)

    def __getitem__(self, codepoint: int):
        # 兼容舊式 translate(table) 介面
        return self._table.get(codepoint)


# 使用範例
if __name__ == "__main__":
    only_vowels = CharFilter('aeiouyAEIOUY')
    print(only_vowels('Four score and seven years ago'))   # ouoeaeeyeaao
    print(only_vowels('Tiger, tiger burning bright'))      # ieieuii

    # 僅保留數字
    only_digits = CharFilter('0123456789')
    print(only_digits('Order #1234-5678'))                 # 12345678

    # 僅保留 ASCII 字母數字
    import string
    alnum = CharFilter(string.ascii_letters + string.digits)
    print(alnum('Hello 世界! 123'))                        # Hello123

替代方案對比

方法時間複雜度記憶體適用場景
str.translate(table)O(n) C層級64KB (dict) / 256KB (list)**大量字串、固定字元集、效能關鍵**
''.join(c for c in s if c in allowed)O(n) Python層級O(1)字元集動態變化、短字串、原型開發
re.sub(f'[^{re.escape(allowed)}]', '', s)O(n) 正則引擎編譯後模式複雜模式、需 Unicode 分類 (\p{L})
filter(lambda c: c in allowed, s)O(n) Python層級O(1)函數式風格、串流處理

進階:支援完整 Unicode (含補充平面)


class FullUnicodeFilter:
    def __init__(self, keep_chars: str):
        self._keep = set(keep_chars)
        # 處理 BMP
        self._bmp_table = {cp: None for cp in range(0x10000) if chr(cp) not in self._keep}

    def __call__(self, s: str) -> str:
        # 先處理 BMP
        res = s.translate(self._bmp_table)
        # 再處理補充平面字元 (逐字元檢查,數量極少)
        if any(ord(c) >= 0x10000 for c in res):
            res = ''.join(c for c in res if c in self._keep)
        return res

效能基準 (參考)

字串長度 1,000,000,保留 26 英文字母
translate (dict table) : ~12 ms
generator + join       : ~85 ms
re.sub                 : ~45 ms
filter + join          : ~90 ms

translate 快 **5-8 倍**,且可重用表物件。

copyright © 萬盛學電腦網 all rights reserved