Python 获取中文字拼音首个字母的方法

yipeiwu_com5年前Python基础

Python:3.5

代码如下:

def single_get_first(unicode1):
 str1 = unicode1.encode('gbk')
 try:
 ord(str1)
 return str1.decode('gbk')
 except:
 asc = str1[0] * 256 + str1[1] - 65536
 if asc >= -20319 and asc <= -20284:
 return 'a'
 if asc >= -20283 and asc <= -19776:
 return 'b'
 if asc >= -19775 and asc <= -19219:
 return 'c'
 if asc >= -19218 and asc <= -18711:
 return 'd'
 if asc >= -18710 and asc <= -18527:
 return 'e'
 if asc >= -18526 and asc <= -18240:
 return 'f'
 if asc >= -18239 and asc <= -17923:
 return 'g'
 if asc >= -17922 and asc <= -17418:
 return 'h'
 if asc >= -17417 and asc <= -16475:
 return 'j'
 if asc >= -16474 and asc <= -16213:
 return 'k'
 if asc >= -16212 and asc <= -15641:
 return 'l'
 if asc >= -15640 and asc <= -15166:
 return 'm'
 if asc >= -15165 and asc <= -14923:
 return 'n'
 if asc >= -14922 and asc <= -14915:
 return 'o'
 if asc >= -14914 and asc <= -14631:
 return 'p'
 if asc >= -14630 and asc <= -14150:
 return 'q'
 if asc >= -14149 and asc <= -14091:
 return 'r'
 if asc >= -14090 and asc <= -13119:
 return 's'
 if asc >= -13118 and asc <= -12839:
 return 't'
 if asc >= -12838 and asc <= -12557:
 return 'w'
 if asc >= -12556 and asc <= -11848:
 return 'x'
 if asc >= -11847 and asc <= -11056:
 return 'y'
 if asc >= -11055 and asc <= -10247:
 return 'z'
 return ''


def getPinyin(string):
 if string == None:
 return None
 lst = list(string)
 charLst = []
 for l in lst:
 charLst.append(single_get_first(l))
 return ''.join(charLst)


if __name__ == '__main__':
 print(getPinyin('你好'))

运行结果:

Python 中文字拼音首个字母

以上这篇Python 获取中文字拼音首个字母的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

ML神器:sklearn的快速使用及入门

ML神器:sklearn的快速使用及入门

传统的机器学习任务从开始到建模的一般流程是:获取数据 -> 数据预处理 -> 训练建模 -> 模型评估 -> 预测,分类。本文我们将依据传统机器学习的流程,看看在...

Django实现CAS+OAuth2的方法示例

CAS Solution 使用CAS作为认证协议。 A作为主要的认证提供方(provider)。 A保留用户系统,其余系统如xxx/www不保留用户系统,即Provid...

分享Python字符串关键点

字符串是 Python 中最常用的数据类型。我们可以使用引号来创建字符串。python字符串关键点有下面几点: 1.一些引号分隔的字符 你可以把字符串看出是Python的一种数据类型...

Python编程中的反模式实例分析

本文实例讲述了Python编程中的反模式。分享给大家供大家参考。具体分析如下: Python是时下最热门的编程语言之一了。简洁而富有表达力的语法,两三行代码往往就能解决十来行C代码才能解...

Python多线程处理实例详解【单进程/多进程】

Python多线程处理实例详解【单进程/多进程】

本文实例讲述了Python多线程处理操作。分享给大家供大家参考,具体如下: python — 多线程处理 1、一个进程执行完后,继续下一个进程 root@72132server:~#...