利用 GB2312 編碼中漢字的區位碼與拼音的對應關係:每個漢字佔 2 位元組,區碼 = 高位元組 - 160,位碼 = 低位元組 - 160,綜合索引 = (區碼-1)*94 + (位碼-1)。預先建立「索引 → 拼音」的字典表,查表即得拼音。此法無需外部元件、效能極佳。
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
原始碼中的字典僅含部分拼音鍵值,實務上建議:
pinyin4net, node-pinyin) 匯出完整 GB2312/GBK 映射表 (CSV/JSON)。pinyin_dict.inc,載入 Dictionary。dict(Idx),Idx = (High-160)*256 + (Low-160)。Scripting.Dictionary 的 Exists 快速判斷。若專案已遷移至 ASP.NET,請直接使用 Microsoft.International.Converters.PinyinConverter 或第三方庫 (如 Pinyin4net),支援多音字、聲調、分詞,準確度遠高於簡易查表法。