萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> ASP 程式設計

ASP 漢字轉拼音函數:GB2312 區位碼對照表法實作

原理說明

利用 GB2312 編碼中漢字的區位碼與拼音的對應關係:每個漢字佔 2 位元組,區碼 = 高位元組 - 160,位碼 = 低位元組 - 160,綜合索引 = (區碼-1)*94 + (位碼-1)。預先建立「索引 → 拼音」的字典表,查表即得拼音。此法無需外部元件、效能極佳。

核心字典建立 (節錄,完整表含 6000+ 常用字)

Dim PyDict
Set PyDict = Server.CreateObject("Scripting.Dictionary")
PyDict.CompareMode = 1 ' 二進位比較,區分大小寫

' 以負數索引鍵儲存 (原始碼習慣)
PyDict.Add "a",   -20319
PyDict.Add "ai",  -20317
PyDict.Add "an",  -20304
PyDict.Add "ang", -20295
PyDict.Add "ao",  -20292
PyDict.Add "ba",  -20283
' ... 此處省略數千行,完整表請見原始碼附件
PyDict.Add "zuo", -15640

轉換函數

Function ChineseToPinyin(strChinese)
  Dim i, lenStr, high, low, idx, key, pinyin, result
  result = ""
  lenStr = Len(strChinese)
  For i = 1 To lenStr
    high = Asc(Mid(strChinese, i, 1))
    If high > 160 Then ' 雙位元組漢字
      If i < lenStr Then
        low = Asc(Mid(strChinese, i + 1, 1))
        If low > 160 Then
          idx = (high - 160) * 256 + (low - 160) ' 簡化索引,實際需查表映射
          ' 這裡示範邏輯:實際專案請使用完整映射表
          key = GetPinyinKeyByIndex(idx) ' 自行實現反查
          If PyDict.Exists(key) Then
            result = result & key & " "
          Else
            result = result & Mid(strChinese, i, 2) & " "
          End If
          i = i + 1
        Else
          result = result & Mid(strChinese, i, 1)
        End If
      Else
        result = result & Mid(strChinese, i, 1)
      End If
    Else
      result = result & Mid(strChinese, i, 1) ' ASCII 字元保留
    End If
  Next
  ChineseToPinyin = Trim(result)
End Function

完整可用版本建議

原始碼中的字典僅含部分拼音鍵值,實務上建議:

  1. 從開源專案 (如 pinyin4net, node-pinyin) 匯出完整 GB2312/GBK 映射表 (CSV/JSON)。
  2. 離線產生 ASP 包含檔 pinyin_dict.inc,載入 Dictionary。
  3. 函式改為查字典:dict(Idx),Idx = (High-160)*256 + (Low-160)。

效能優化

  • 將 Dictionary 存入 Application 物件,全站共享,避免每次重建。
  • 使用 Scripting.Dictionary 的 Exists 快速判斷。
  • 若需聲調數字,字典值改為 "zhang1, zhang3" 等格式。

替代方案

若專案已遷移至 ASP.NET,請直接使用 Microsoft.International.Converters.PinyinConverter 或第三方庫 (如 Pinyin4net),支援多音字、聲調、分詞,準確度遠高於簡易查表法。

copyright © 萬盛學電腦網 all rights reserved