本文的代码,从https://github.com/cleverdeng/pinyin.py升级得来,针对原文的代码,做了以下升级:

 
 
1
2
3
4
1、可以传入参数firstcode:如果为true,只取汉子的第一个拼音字母;如果为false,则会输出全部拼音;
2、修复:如果为英文字母,则直接输出;
3、修复:如果分隔符为空字符串,仍然能正常输出;
4、升级:可以指定词典的文件路径

代码很简单,直接读取了一个词典(字符和英文的映射),然后挨个替换中文中的拼音即可;

 
 
 
 
 

Python

 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
#!/usr/bin/env python
# -*- coding:utf-8 -*-
 
"""
原版代码:https://github.com/cleverdeng/pinyin.py
 
新增功能:
    1、可以传入参数firstcode:如果为true,只取汉子的第一个拼音字母;如果为false,则会输出全部拼音;
    2、修复:如果为英文字母,则直接输出;
    3、修复:如果分隔符为空字符串,仍然能正常输出;
    4、升级:可以指定词典的文件路径
"""
 
__version__ = '0.9'
__all__ = ["PinYin"]
 
import os.path
 
 
class PinYin(object):
    def __init__(self):
        self.word_dict = {}
 
    def load_word(self, dict_file):
        self.dict_file = dict_file
        if not os.path.exists(self.dict_file):
            raise IOError("NotFoundFile")
 
        with file(self.dict_file) as f_obj:
            for f_line in f_obj.readlines():
                try:
                    line = f_line.split('    ')
                    self.word_dict[line[0]] = line[1]
                except:
                    line = f_line.split('   ')
                    self.word_dict[line[0]] = line[1]
 
 
    def hanzi2pinyin(self, string="", firstcode=False):
        result = []
        if not isinstance(string, unicode):
            string = string.decode("utf-8")
        
        for char in string:
            key = '%X' % ord(char)
            value = self.word_dict.get(key, char)
            outpinyin = str(value).split()[0][:-1].lower()
            if not outpinyin:
                outpinyin = char
            if firstcode:
                result.append(outpinyin[0])
            else:
                result.append(outpinyin)
 
        return result
 
 
    def hanzi2pinyin_split(self, string="", split="", firstcode=False):
        """提取中文的拼音
        @param string:要提取的中文
        @param split:分隔符
        @param firstcode: 提取的是全拼还是首字母?如果为true表示提取首字母,默认为False提取全拼  
        """
        result = self.hanzi2pinyin(string=string, firstcode=firstcode)
        return split.join(result)
 
 
if __name__ == "__main__":
    test = PinYin()
    test.load_word('word.data')
    string = "Java程序性能优化-让你的Java程序更快更稳定"
    print "in: %s" % string
    print "out: %s" % str(test.hanzi2pinyin(string=string))
    print "out: %s" % test.hanzi2pinyin_split(string=string, split="", firstcode=True)
    print "out: %s" % test.hanzi2pinyin_split(string=string, split="", firstcode=False)
 

实例中main函数的代码输出结果

代码使用方法:

如果需要其他的提取,可以修改一下代码实现;

Python中文转拼音代码(支持全拼和首字母缩写)的更多相关文章

  1. PHP:汉字转拼音类(全拼与首字母)

    [php] <?php class GetPingYing { private $pylist = array( 'a'=>-20319,'ai'=>-20317,'an'=> ...

  2. select2 全拼以及首字母

    转自:https://blog.csdn.net/kanhuadeng/article/details/78475317 具体实现方法为: 首先需要在网上下载select2的源码,并引入到项目中,具体 ...

  3. js汉语转拼音(全拼、首字母、拼音首字母)

    新建js文件first_alphabet.js // JavaScript Document // 汉字拼音首字母列表 本列表包含了20902个汉字,用于配合 ToChineseSpell //函数使 ...

  4. java 汉语转拼音(全拼,首字母)

    import java.util.*; import net.sourceforge.pinyin4j.PinyinHelper;import net.sourceforge.pinyin4j.for ...

  5. java根据汉字获取全拼和首字母

    import net.sourceforge.pinyin4j.PinyinHelper; import net.sourceforge.pinyin4j.format.HanyuPinyinCase ...

  6. 【Java】使用pinyin4j获取汉字的全拼或首字母

    汉字转拼音的工具类,常用于做汉字拼音的模糊查询. https://www.cnblogs.com/htyj/p/7891918.html

  7. c#中文转全拼或首拼

    参考:http://www.jb51.net/article/42217.htmhttp://blog.csdn.net/cstester/article/details/4758172 Chines ...

  8. NPinyin 中文转换拼音代码

    Mono 3.2 测试NPinyin 中文转换拼音代码   C#中文转换为拼音NPinyin代码  在Mono 3.2下运行正常,Spacebuilder 有使用到NPinyin组件,代码兼容性没有问 ...

  9. Java获取中文拼音、中文首字母缩写和中文首字母

    获取中文拼音(如:广东省 -->guangdongsheng) /** * 得到中文全拼 * @param src 需要转化的中文字符串 * @return */ public static S ...

随机推荐

  1. LiteQuery MAX(Integer)、MAX(String) 判断是否返回值

    unit Unit6; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System ...

  2. MySQL 由 5.7 升级为 8.0 之后,Laravel 的配置改动

    开发机上升级了 MySQL 8.0, 原有的 Laravel 5.5 项目就启动失败了. 报错信息是: [2018-05-30 11:17:37] local.ERROR: SQLSTATE[4200 ...

  3. 双线程 线性dp 传纸条

    /* 两种做法:一是暴力dp[i][j][k][l] 二是以走的步数k作为阶段, dp[k][i][j]表示走到第k步,第一个人横坐标走到i,第二个人横坐标走到j 可以以此推出第第一个人的坐标为[i, ...

  4. poj2828 伸展树模拟

    用伸展树模拟插队比线段树快乐3倍.. 但是pojT了.别的oj可以过,直接贴代码. 每次更新时,找到第pos个人,splay到根,然后作为新root的左子树即可 #include<iostrea ...

  5. pytest七:assert

    断言是写自动化测试基本最重要的一步,一个用例没有断言,就失去了自动化测试的意义了.什么是断言呢?简单来讲就是实际结果和期望结果去对比,符合预期那就测试 pass,不符合预期那就测试 failed py ...

  6. hdu 1005 根据递推公式构造矩阵 ( 矩阵快速幂)

    f(1) = 1, f(2) = 1, f(n) = (A * f(n - 1) + B * f(n - 2)) mod 7. Sample Input1 1 3 //a b n1 2 100 0 0 ...

  7. python 线程间通信之Condition, Queue

    Event 和 Condition 是threading模块原生提供的模块,原理简单,功能单一,它能发送 True 和 False 的指令,所以只能适用于某些简单的场景中. 而Queue则是比较高级的 ...

  8. Linux学习 用户管理

    0.新建用户 sudo useradd -d /home/zookeeper -m zookeeper -d 指定用户组目录 -m 如果前面指定的用户组目录不存在,就创建改目录 passwd 1./e ...

  9. [转]oracle10客户端PL/SQL Developer如何连接远程服务器上的oracle数据库

    时间:2013年8月21日 前提条件:假设你已经安装好了oracle和PL/SQL Developer,知道远程服务器的IP和数据库端口,知道远程服务器上的oracle数据库名和密码 如何用PL/SQ ...

  10. C#编程的语法积累(一)

    1.自动属性 之前的实现方式: private int id; public int Id { set {id = value;} get {return id;} } 现在可通过自动属性实现: pu ...