python实现按中文拼音对字符串排序

349次阅读
没有评论

python实现按中文拼音对字符串排序

安装中文库

(推荐教程:python基础教程)

sudo apt-get update
sudo apt-get install language-pack-zh-hans-base
sudo dpkg-reconfigure locales

使用

import locale
locale.setlocale(locale.LC_COLLATE, 'zh_CN.UTF8')
cmp = locale.strcoll

courses.sort(lambda x, y: cmp(x.course_name, y.course_name))

测试用例

输入

# -*- coding: utf-8 -*-
import locale
locale.setlocale(locale.LC_COLLATE, 'zh_CN.UTF8')
cmp = locale.strcoll

items = list('自挂东南枝'.decode('utf-8'))
print 'before'.center(10, '=')
print ''.join(items)
items.sort(lambda x, y: cmp(x, y))
print 'after'.center(10, '=')
print ''.join(items)

输出

==before==
自挂东南枝
==after===
东挂南枝自
神龙|纯净稳定代理IP免费测试>>>>>>>>天启|企业级代理IP免费测试>>>>>>>>IPIPGO|全球住宅代理IP免费测试

相关文章:

版权声明:程序人生2022-12-08发表,共计674字。
新手QQ群:570568346,欢迎进群讨论 Python51学习