网络编程
位置:首页>> 网络编程>> Python编程>> Python实现按中文排序的方法示例

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

作者:tian_shl  发布时间:2023-11-29 15:19:22 

标签: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===
东挂南枝自

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

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

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

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

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

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

来源:https://blog.csdn.net/xiaobuding007/article/details/78224159

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com