蟒蛇 – 用编号将拼音拼写为拼音

前端之家收集整理的这篇文章主要介绍了蟒蛇 – 用编号将拼音拼写为拼音前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
是否有使用 Python的脚本,库或程序,或BASH工具(例如awk,perl,sed),可以将编号的拼音(例如,dian4 nao3)正确地转换成带有音标(例如diànnǎo)的UTF-8拼音?

我发现了以下示例,但是它们需要PHP或#C:

> PHP Convert numbered to accentuated Pinyin?
> #C Any libraries to convert number pinyin to pinyin with tone markings?

我还发现了各种在线工具,但是它们无法处理大量的转换.

我有一些Python 3代码,这样做很小,直接放在这里的答案中.
  1. PinyinToneMark = {
  2. 0: "aoeiuv\u00fc",1: "\u0101\u014d\u0113\u012b\u016b\u01d6\u01d6",2: "\u00e1\u00f3\u00e9\u00ed\u00fa\u01d8\u01d8",3: "\u01ce\u01d2\u011b\u01d0\u01d4\u01da\u01da",4: "\u00e0\u00f2\u00e8\u00ec\u00f9\u01dc\u01dc",}
  3.  
  4. def decode_pinyin(s):
  5. s = s.lower()
  6. r = ""
  7. t = ""
  8. for c in s:
  9. if c >= 'a' and c <= 'z':
  10. t += c
  11. elif c == ':':
  12. assert t[-1] == 'u'
  13. t = t[:-1] + "\u00fc"
  14. else:
  15. if c >= '0' and c <= '5':
  16. tone = int(c) % 5
  17. if tone != 0:
  18. m = re.search("[aoeiuv\u00fc]+",t)
  19. if m is None:
  20. t += c
  21. elif len(m.group(0)) == 1:
  22. t = t[:m.start(0)] + PinyinToneMark[tone][PinyinToneMark[0].index(m.group(0))] + t[m.end(0):]
  23. else:
  24. if 'a' in t:
  25. t = t.replace("a",PinyinToneMark[tone][0])
  26. elif 'o' in t:
  27. t = t.replace("o",PinyinToneMark[tone][1])
  28. elif 'e' in t:
  29. t = t.replace("e",PinyinToneMark[tone][2])
  30. elif t.endswith("ui"):
  31. t = t.replace("i",PinyinToneMark[tone][3])
  32. elif t.endswith("iu"):
  33. t = t.replace("u",PinyinToneMark[tone][4])
  34. else:
  35. t += "!"
  36. r += t
  37. t = ""
  38. r += t
  39. return r

这处理ü,u:和v,我遇到过的所有. Python 2兼容性将需要进行小的修改.

猜你在找的Bash相关文章