知行编程网知行编程网  2022-11-25 03:00 知行编程网 隐藏边栏  30 
文章评分 0 次,平均分 0.0
导语: 本文主要介绍了关于python中文生僻字的识别的相关知识,希望可以帮到处于编程学习途中的小伙伴

python识别生僻汉字


问题点

本来考虑用正则表达式判断中文,因为在网上查到的匹配中文是[\u4e00-\u9fa5]。然后码的差不多了,发现有些生僻字已经不在这个范围内了。


识别方法

在utf-8字符编码下,一个汉字占3个字节,但字符长度只有1个字节。

1、分析中文的方法是否可以灵活为len(bytes(str,'utf-8)==3 and len(string)==1。


2、文本写作判断中文后,如果是汉字str.ljust(5),否则为str.ljust(6)。


因为一个汉字占两个字符的长度。


实例

from pypinyin import pinyin
import re
 
 
class ChangePinyin:
    def __init__(self, filename):
        self.file = filename
        self.lyric = self.read_file()
        self.pinyin = []
 
    def read_file(self):
        with open(self.file, encoding='utf-8') as f:
            return f.readlines()
 
    def write_file(self):
        with open('New_%s' % self.file, 'w', encoding='utf-8') as f:
            print(self.lyric)
            for line in self.lyric:
                # print(line)
                if line.strip() == '':
                    continue
                _new_line = re.sub(r'\s', '', line)
                # 行内容转拼音
                _pinyin = ''.join(map(lambda x: x[0].ljust(6), pinyin(_new_line)))
                # 根据中英文,将行内容进行字符与汉字的拆分
                _lyric = self.split_words(_new_line)
                f.write('%s\n%s\n' % (_pinyin, _lyric))
 
    @staticmethod
    def split_words(words):
        word_list = ""
        tmp = ""
        for string in words:
            if len(bytes(string, 'utf-8')) == 3 and len(string) == 1:
                if tmp != '':
                    word_list += tmp.ljust(6)
                    tmp = ""
                word_list += string.ljust(5)
            else:
                tmp += string
        return word_list
 
 
if __name__ == '__main__':
    Main = ChangePinyin('lyric.txt')
    Main.write_file()


本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。

本文为原创文章,版权归所有,欢迎分享本文,转载请保留出处!

知行编程网
知行编程网 关注:1    粉丝:1
这个人很懒,什么都没写
扫一扫二维码分享