Skip to content

Instantly share code, notes, and snippets.

@ciaranchen
Created August 4, 2021 10:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ciaranchen/0b0a8763462eb55f9722318dae7e462f to your computer and use it in GitHub Desktop.
Save ciaranchen/0b0a8763462eb55f9722318dae7e462f to your computer and use it in GitHub Desktop.
小鹤双拼-pypinyin

利用pypinyin库,列出一段文字用小鹤打字需要敲击的按键。

{
"fu": {
"u": "sh",
"i": "ch",
"v": "zh"
},
"yr": {
"q": "iu",
"w": "ei",
"e": "e",
"r": "uan",
"t": ["ue", "ve"],
"y": "un",
"u": "u",
"i": "i",
"o": ["uo", "o"],
"a": "a",
"s": ["ong", "iong"],
"d": "ai",
"f": "en",
"g": "eng",
"h": "ang",
"j": "an",
"k": ["uai", "ing"],
"l": ["uang", "iang"],
"z": "ou",
"x": ["ua", "ia"],
"c": "ao",
"v": ["ui", "v"],
"b": "in",
"n": "iao",
"m": "ian"
}
}
from pypinyin import pinyin, lazy_pinyin, Style
from pypinyin.style import register
from pypinyin.contrib.tone_convert import to_normal
import json, sys
with open('data.json') as f:
data = json.load(f)
def rev_func(data):
res = {}
for k, v in data.items():
if isinstance(v, list):
for vi in v:
res[vi] = k
else:
res[v] = k
return res
rev_yr = rev_func(data['yr'])
rev_fu = rev_func(data['fu'])
def split_yf(yin):
for f in rev_fu:
if yin.startswith(f):
return f, yin[2:]
if yin.startswith('a') or yin.startswith('o') or yin.startswith('e'):
return '', yin
else:
return yin[0], yin[1:]
@register('xhup')
def kiss(pinyin, **kwargs):
pinyin = to_normal(pinyin)
f, y = split_yf(pinyin)
ry, rf = rev_yr[y] if y in rev_yr else y, rev_fu[f] if f in rev_fu else f
return rf+ry
# pinyin = lazy_pinyin(s, Style.NORMAL, strict=False)
# for yin in pinyin:
# f, y = split_yf(yin)
# ry, rf = rev_yr[y] if y in rev_yr else y, rev_fu[f] if f in rev_fu else f
# print(rf+ry)
if __name__ == '__main__':
s = sys.argv[1] if len(sys.argv) >= 2 else '乌鸦喝水'
print(s)
print(lazy_pinyin(s, style='xhup'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment