码迷,mamicode.com
首页 > 编程语言 > 详细

Python 获得汉字笔画

时间:2018-05-06 12:13:42      阅读:2823      评论:0      收藏:0      [点我收藏+]

标签:index   映射   def   int   包括   open   strip()   data   art   

通过unihan的文件来实现。
只要是unihan中有kTotalStrokes字段,获取起笔画数。
Hash也是非常简单清楚的,但想到这些unicode其实会有一个分布规律,就记录了一下,
利用此性质通过数组方式来获取笔画。

记录了一下unicode的范围
start: [13311, 19968, 63744, 131072, 173824, 177984, 178208, 194995]
end : [19893, 40917, 64045, 173782, 177972, 178205, 183969, 194998]

总共包括80682个存在笔画数的unicode码,包含CJKV。
64045-131072中间都没有此字段,就分了两部分。

此处使用python3 Demo实现,原理非常简单:使用数组保持笔画,将unicode映射到数组index,即可获取对应笔画数

def get_stroke(c):
    # 如果返回 0, 则也是在unicode中不存在kTotalStrokes字段
    strokes = []
    with open(strokes_path, ‘r‘) as fr:
        for line in fr:
            strokes.append(int(line.strip()))

    unicode_ = ord(c)

    if 13312 <= unicode_ <= 64045:
        return strokes[unicode_-13312]
    elif 131072 <= unicode_ <= 194998:
        return strokes[unicode_-80338]
    else:
        print("c should be a CJK char, or not have stroke in unihan data.")
        # can also return 0

strokes_path: https://github.com/helmz/Corpus/blob/master/zh_dict/strokes.txt
"按照unicode顺序排列的笔画数"

Python 获得汉字笔画

标签:index   映射   def   int   包括   open   strip()   data   art   

原文地址:https://www.cnblogs.com/Comero/p/8997585.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!