• 技术文章 >Python技术 >Python基础教程

    python中文生僻字的识别

    小妮浅浅小妮浅浅2021-09-16 09:25:36原创4468

    问题点

    本来考虑用正则来判断中文,因为网上发现正则的匹配中文是[\u4e00-\u9fa5]。接着代码都快写完了,发现有些生僻字不再在这个范围内。

    识别方法

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

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

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

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

    实例

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    23

    24

    25

    26

    27

    28

    29

    30

    31

    32

    33

    34

    35

    36

    37

    38

    39

    40

    41

    42

    43

    44

    45

    46

    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()

    以上就是python中文生僻字的识别,希望对大家有所帮助。更多Python学习指路:python基础教程

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

    专题推荐:python识别
    上一篇:python拼音模块的特性 下一篇:python字符串常用技巧的总结

    相关文章推荐

    • python类属性的两种分类• python抽象类的使用• python中XML有哪些解析模块的方法• python中XML删除元素• python套接字编程的服务器和客户端• Python如何搭建gRPC服务• Python lambda的速写用法• Python如何实现打字训练的程序• Python列表推导式如何使用• python中pyquery初始化的方法• python中pyquery的CSS选择器用法• python GUI编程有哪些模板• python拼音模块的特性

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网