Python实现按中文排序的方法示例

yipeiwu_com6年前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===
东挂南枝自

本机测试输出效果如下图:

PS:这里再为大家推荐2款比较实用的相关在线排序工具供大家参考使用:

在线中英文根据首字母排序工具:
http://tools.jb51.net/aideddesign/zh_paixu

在线文本倒序翻转排序工具:
http://tools.jb51.net/aideddesign/flipped_txt

更多关于Python相关内容感兴趣的读者可查看本站专题:《Python列表(list)操作技巧总结》、《Python数组操作技巧总结》、《Python字符串操作技巧汇总》、《Python函数使用技巧总结》、《Python入门与进阶经典教程》及《Python数据结构与算法教程

希望本文所述对大家Python程序设计有所帮助。

相关文章

python 实现识别图片上的数字

python 实现识别图片上的数字

Python 3.6 版本 Pytesseract 图像验证码识别 环境: (1) win7 64位 (2) Idea (3) python 3.6 (4) pip install pi...

使用python分析git log日志示例

用git来管理工程的开发,git log是非常有用的‘历史'资料,需求就是来自这里,我们希望能对git log有一个定制性强的过滤。此段脚本就是在完成这种类型的任务。对于一个repo所有...

TF-IDF算法解析与Python实现方法详解

TF-IDF算法解析与Python实现方法详解

TF-IDF(term frequency–inverse document frequency)是一种用于信息检索(information retrieval)与文本挖掘(text m...

python中set()函数简介及实例解析

set函数也是python内置函数的其中一个,属于比较基础的函数。其具体介绍和使用方法,下面进行介绍。 set() 函数创建一个无序不重复元素集,可进行关系测试,删除重复数据,还可以计算...

python增加矩阵维度的实例讲解

numpy.expand_dims(a, axis) Examples >>> x = np.array([1,2]) >>> x.shape...