-
Notifications
You must be signed in to change notification settings - Fork 2
/
Hanzi2Pinyin.h
61 lines (51 loc) · 1.6 KB
/
Hanzi2Pinyin.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
/**********************************************************
* Author: Qt君
* 微信公众号: Qt君(首发)
* QQ群: 732271126
* Email: 2088201923@qq.com
* Github: https://github.com/aeagean/Hanzi2Pinyin
**********************************************************/
#ifndef HANZI2PINYIN_H
#define HANZI2PINYIN_H
#include <QMap>
#include <QFile>
class Hanzi2Pinyin
{
public:
Hanzi2Pinyin()
{
}
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;
}
};
#endif // HANZI2PINYIN_H