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

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

 

posted @ 2022-07-14 17:55  飞扬92  阅读(499)  评论(3编辑  收藏  举报