python中将汉字转换成拼音

python3.4环境,在3.0以下的版本有些地方不一样,可自行修改。

可转换全部文章,唯一缺陷就是标点符号正常无法转换。以后想到再做修改。

 1 #coding=gbk
 2 '''
 3 Created on 2014-8-29
 4 
 5 @author: Administrator
 6 '''
 7 #import os
 8 
 9 def convert(ch):
10     """该函数通过输入汉字返回其拼音,如果输入多个汉字,则返回第一个汉字拼音.
11        如果输入数字字符串,或者输入英文字母,则返回其本身(英文字母如果为大写,转化为小写)
12     """
13     length = len('') #测试汉字占用字节数,utf-8,汉字占用3字节.bg2312,汉字占用2字节
14     intord = ord(ch[0:1])
15     if (intord >= 48 and intord <= 57):
16         return ch[0:1]
17     if (intord >= 65 and intord <=90 ) or (intord >= 97 and intord <=122):
18         return ch[0:1].lower()
19     ch = ch[0:len(ch)] #多个汉字只获取第一个
20     with open(r'C:\\convert-utf-8.txt') as f:
21         for line in f:
22             if ch in line:
23                 return line[length:len(line)-2]
24 
25 path = 'C:\\test\\申.txt'
26 f = open(path)
27 p = f.read()
28 for i in p:
29     print(convert(i),end='')

代码里面的convert-utf-8.txt是一个转换文件,可以在我网盘里面下载。

至于申.txt里面是一段中文和数字组合,测试用的,可以自己diy,嘿嘿。

网盘地址:http://pan.baidu.com/s/1eQGLDaq

posted @ 2014-09-08 11:44  猫为什么不能遛  阅读(448)  评论(0编辑  收藏  举报