Python 汉字的排序问题

2022/7/15 1:20:04

本文主要是介绍Python 汉字的排序问题,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

char=['赵','钱','孙','李','佘']
char.sort()
for item in char:
     print(item,ord(item))

# 佘 20312
# 孙 23385
# 李 26446
# 赵 36213
# 钱 38065

 

汉字排序是按照unicode数值排序

ord() 函数是 chr() 函数(对于 8 位的 ASCII 字符串)的配对函数,它以一个字符串(Unicode 字符)作为参数,返回对应的 ASCII 数值,或者 Unicode 数值。

解决方案,使用汉字转拼音库pypinyin ,得到拼音及音调

from itertools import chain
from pypinyin import pinyin, Style


def to_pinyin(s):
    return ''.join(chain.from_iterable(pinyin(s, style=Style.TONE3)))
print(sorted(char))  
print(sorted(char, key=to_pinyin))  

# ['佘', '孙', '李', '赵', '钱']
# ['李', '钱', '佘', '孙', '赵']

 



这篇关于Python 汉字的排序问题的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程