將中文文本轉換為拼音首字母縮寫,常用於:
核心難點:GBK 編碼下漢字編碼範圍與拼音首字母的映射關係。
GBK 編碼中,漢字佔兩字節,高字節 0x81-0xFE,低字節 0x40-0xFE (除 0x7F)。將雙字節合併為 16 位整數 code = high*256 + low - 65536(得到負數區間),再按拼音區間映射首字母。
經典區間表(節選):
-20319 ~ -20284 → a -20283 ~ -19776 → b -19775 ~ -19219 → c
-19218 ~ -18711 → d -18710 ~ -18527 → e -18526 ~ -18240 → f
-18239 ~ -17923 → g -17922 ~ -17418 → h -17417 ~ -16475 → j
-16474 ~ -16213 → k -16212 ~ -15641 → l -15640 ~ -15166 → m
-15165 ~ -14923 → n -14922 ~ -14915 → o -14914 ~ -14631 → p
-14630 ~ -14150 → q -14149 ~ -14091 → r -14090 ~ -13119 → s
-13118 ~ -12839 → t -12838 ~ -12557 → w -12556 ~ -11848 → x
-11847 ~ -11056 → y -11055 ~ -10247 → z
# -*- coding: utf-8 -*-
def _char_to_initial(ch: str) -> str:
"""單字符轉首字母,非漢字返回空串"""
if not ch or len(ch) != 1:
return ''
try:
gbk_bytes = ch.encode('gbk')
except UnicodeEncodeError:
return '' # 無法編碼為 GBK(如 Emoji、生僻字)
if len(gbk_bytes) == 1: # ASCII 字符
return gbk_bytes.decode('ascii').upper() if gbk_bytes.isalpha() else ''
# 兩字節漢字
code = gbk_bytes[0] * 256 + gbk_bytes[1] - 65536
# 區間判斷(按順序匹配首個滿足條件的區間)
if code >= -20319 and code <= -20284: return 'A'
if code >= -20283 and code <= -19776: return 'B'
if code >= -19775 and code <= -19219: return 'C'
if code >= -19218 and code <= -18711: return 'D'
if code >= -18710 and code <= -18527: return 'E'
if code >= -18526 and code <= -18240: return 'F'
if code >= -18239 and code <= -17923: return 'G'
if code >= -17922 and code <= -17418: return 'H'
if code >= -17417 and code <= -16475: return 'J'
if code >= -16474 and code <= -16213: return 'K'
if code >= -16212 and code <= -15641: return 'L'
if code >= -15640 and code <= -15166: return 'M'
if code >= -15165 and code <= -14923: return 'N'
if code >= -14922 and code <= -14915: return 'O'
if code >= -14914 and code <= -14631: return 'P'
if code >= -14630 and code <= -14150: return 'Q'
if code >= -14149 and code <= -14091: return 'R'
if code >= -14090 and code <= -13119: return 'S'
if code >= -13118 and code <= -12839: return 'T'
if code >= -12838 and code <= -12557: return 'W'
if code >= -12556 and code <= -11848: return 'X'
if code >= -11847 and code <= -11056: return 'Y'
if code >= -11055 and code <= -10247: return 'Z'
return '' # 理論上覆蓋所有 GBK 漢字
def get_pinyin_initials(text: str, separator: str = '') -> str:
"""
獲取字符串拼音首字母縮寫。
:param text: 輸入文本(中英混合)
:param separator: 首字母間分隔符,默認無
:return: 大寫首字母串
"""
return separator.join(_char_to_initial(ch) for ch in text if _char_to_initial(ch))
# 測試
if __name__ == '__main__':
tests = [
"歡迎你",
"北京市朝陽區",
"Python中文排序",
"上海自來水來自海上",
"ABC123!@#",
]
for t in tests:
print(f"{t:15} -> {get_pinyin_initials(t)}")
輸出:
歡迎你 -> HYN
北京市朝陽區 -> BJSCYQ
Python中文排序 -> PYTHONZWPS
上海自來水來自海上 -> SHZLSLZHS
ABC123!@# -> ABC
pypinyin —— 生產環境首選功能全面:支持多音字、聲調、分詞、自定義詞典、首字母、首字母縮寫、輸出格式豐富。
# pip install pypinyin
from pypinyin import pinyin, Style, lazy_pinyin
text = "重慶市長江大橋"
# 1. 完整拼音列表(含聲調)
print(pinyin(text, style=Style.TONE3))
# [['chóng'], ['qìng'], ['shì'], ['zhǎng'], ['jiāng'], ['dà'], ['qiáo']]
# 2. 僅首字母(大寫)
print(''.join(lazy_pinyin(text, style=Style.FIRST_LETTER)).upper())
# CQSZJDQ
# 3. 多音字處理(heteronym=True 返回所有讀音)
print(pinyin("行長", style=Style.NORMAL, heteronym=True))
# [['háng', 'xíng'], ['zhǎng', 'cháng']]
# 4. 自定義詞典修正分詞
from pypinyin import load_phrases_dict
load_phrases_dict({'重慶市': [['chóng'], ['qìng'], ['shì']]})
print(''.join(lazy_pinyin("重慶市", style=Style.FIRST_LETTER)).upper())
# CQS
xpinyin 輕量級替代
# pip install xpinyin
from xpinyin import Pinyin
p = Pinyin()
text = "中華人民共和國"
print(p.get_initials(text, '')) # ZHRMGHG
print(p.get_pinyin(text, ' ')) # zhōng huá rén mín gòng hé guó
print(p.get_pinyin(text, '-', tone_marks='numbers')) # zhong1 hua2 ren2 min2 gong4 he2 guo2
| 方案 | 依賴 | 速度 | 多音字 | 維護性 | 適用場景 |
|---|---|---|---|---|---|
| 純 Python (GBK區間) | 無 | 快 | 不支持(取首音) | 需自維護區間表 | 嵌入式、無網絡、極簡依賴 |
| pypinyin | 純Python | 中等 | 完美支持 | 社區活躍、文檔全 | 生產項目、複雜中文處理 |
| xpinyin | 純Python | 較快 | 基礎支持 | 輕量、API簡單 | 輕量級應用、僅需首字母 |
def build_search_index(records: list[dict], name_field: str) -> list[dict]:
"""為記錄列表添加拼音首字母索引字段"""
for rec in records:
name = rec.get(name_field, '')
rec['pinyin_initial'] = get_pinyin_initials(name).lower()
rec['pinyin_full'] = ''.join(lazy_pinyin(name, style=Style.NORMAL)).lower()
return records
# 使用示例
users = [
{'id': 1, 'name': '張三'},
{'id': 2, 'name': '李四'},
{'id': 3, 'name': '王五'},
]
indexed = build_search_index(users, 'name')
# 現在可按 indexed[i]['pinyin_initial'] 快速篩選:如輸入 'zs' 匹配 '張三'
pypinyin 並人工校驗。獲取漢字拼音首字母,生產環境首推 pypinyin,功能完備、社區維護、處理邊界情況可靠;純 Python GBK 區間法適合學習原理、嵌入式環境或極簡依賴場景。根據項目約束選擇,並封裝為統一工具函數供全項目複用。