發佈 | 漢字轉拼音工具

經過查找漢字拼音庫實現實時漢字轉拼音的功能。

demo.gif

實現

  • 加載漢字拼音對照文件pinyin.txt(4萬+漢字拼音對照)到QMap容器。
  • 遍歷QMap容器的漢字從而找到對應的拼音,如找不到該漢字將原樣輸出。
  • 部分pinyin.txt內容:(https://github.com/mozillazg/...
líng,yuán,xīng 〇
qiū 㐀
tiàn 㐁
kuà 㐄
wǔ 㐅
yǐn 㐆
yí 㐌
xié 㐖
chóu 㐜
nuò 㐡
dān,qiú 㐤
xù 㐨
xíng 㐩
xiōng 㐫
liú 㐬
lǐn 㐭

核心代碼

class Hanzi2Pinyin
{
public:
    static QString find(const QString &hanzi)
    {
        static QMap<QString, QStringList> map = loadHanziTable(":/pinyin.txt");
        QString output;
        QStringList stringList = hanzi.split("");

        /* 遍歷查找漢字-拼音對照表的內容並將漢字替換爲拼音 */
        for (const QString &str : stringList) {
            if (map.contains(str))
                output += map[str].first();
            else
                output += str;
        }

        return output;
    }

private:
    /* 加載漢字對照表 */
    static QMap<QString, QStringList> loadHanziTable(const QString &fileName)
    {
        QMap<QString, QStringList> map;
        QFile file(fileName);
        if (!file.open(QFile::ReadOnly | QFile::Text)) {
            qDebug("File: '%s' open failed!", file.fileName().toStdString().c_str());
            return map;
        }

        /* 讀取漢字對照表文件並轉換爲QMap存儲 */
        while(!file.atEnd()) {
            QString content = QString::fromUtf8(file.readLine());
            map[content.split(" ").last().trimmed()] = content.split(" ").first().split(",");
        }

        file.close();

        return map;
    }
};

源碼地址

  歡迎你們一塊兒協做完善。
https://github.com/aeagean/Ha...git

相關文章
相關標籤/搜索