如何将汉字音译为注音(Java)

问题描述 投票:0回答:1

如何将中文繁体字或简体字转换为注音注音?

示例

# simplified
没关系 --> ㄇㄟˊㄍㄨㄢㄒㄧ

# traditional
沒關係 --> ㄇㄟˊㄍㄨㄢㄒㄧ
java chinese-locale transliteration bopomofo
1个回答
3
投票

使用Python

dragonmapper模块进行汉字到注音的转换(在内部它首先转换为拼音,然后转换为注音):

# install dependencies: pip install dragonmapper

from dragonmapper import hanzi

hanzi.to_zhuyin('太阳')
>>> 'ㄊㄞˋ ㄧㄤ˙'

使用Java

可能的顺序:

  1. 使用 pinyin4j (java)、pypinyin (python) 等将中文文本(简体或繁体)转换为拼音
  2. 使用根据此逻辑创建的正则表达式对编号拼音进行标记(生成最终正则表达式)。
  3. 使用记录的映射将拼音标记替换为注音,例如 http://www.pinyin.info/romanization/bopomofo/basic.htmlhttps://terpconnect.umd.edu/~nsw/chinese/pinyin.htm .

步骤 #1 的可能场景:

Java代码

HanyuPinyinOutputFormat outputFormat = new HanyuPinyinOutputFormat();
outputFormat.setToneType(HanyuPinyinToneType.WITH_TONE_NUMBER);
outputFormat.setVCharType(HanyuPinyinVCharType.WITH_U_AND_COLON);
outputFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);

String[] pinyin = PinyinHelper.toHanyuPinyinStringArray(chineseText, outputFormat);

Python代码

from pypinyin import pinyin

hanzi_text = '當然可以'
pinyin_text = ' '.join([seg[0] for seg in pinyin(hanzi_text)])
print(pinyin_text)

步骤 #2 的场景:

如果您在第 1 步中生成了拼音段列表,您现在可以将拼音分成段并使用诸如 this onethis one(js 格式)之类的映射来替换它们。

替代方法

另一种解决方案是使用任何可用的映射将汉字直接映射到注音,例如:https://github.com/osfans/rime-tool/blob/master/data/y/taiwan.dict.yaml 。缺点是(使用这个特定的源)这只会处理简体中文,而不会处理繁体字符。

更新: libchewing 项目的映射涵盖简体和繁体字符(加上频率数据和多个字符的特殊情况):https://github.com/chewing/libchewing/blob/master/data/tsi.src(4.9MB) )。为了能够处理分段,您可能还需要寻找一个像样的中文分段库,例如 jieba (python)、jieba-analysis (java) 等。

© www.soinside.com 2019 - 2024. All rights reserved.