码迷,mamicode.com
首页 > 编程语言 > 详细

python中将汉字转换成拼音

时间:2014-09-09 10:35:48      阅读:466      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   os   for   文件   2014   div   

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(rC:\\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

python中将汉字转换成拼音

标签:style   blog   http   color   os   for   文件   2014   div   

原文地址:http://www.cnblogs.com/lovecc/p/3961226.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!