龚哥哥 - 山里男儿 爱生活、做自己!
Python中文转拼音
发表于 2016-11-2 | 浏览(13187) | Python

最近写一个项目的时候,需要将汉字转化成拼音,在github上找到一个现成的库。

Python汉字转拼音 GitHub地址

1、使用如下

from pinyin import PinYin

test = PinYin()
test.load_word()
print test.hanzi2pinyin(string='钓鱼岛是中国的')
print test.hanzi2pinyin_split(string='钓鱼岛是中国的', split="-")

输出
['diao', 'yu', 'dao', 'shi', 'zhong', 'guo', 'de']
'diao-yu-dao-shi-zhong-guo-de'

2、在中文与英文混合的时候英文会丢失,所以我们需要对库进行一点调整。

2.1、hanzi2pinyin方法调整

# 原始
    def hanzi2pinyin(self, string=""):
        result = []
        if not isinstance(string, unicode):
            string = string.decode("utf-8")

        for char in string:
            key = '%X' % ord(char)
            result.append(self.word_dict.get(key, char).split()[0][:-1].lower())

        return result

# 调整后
    def hanzi2pinyin(self, string=""):
        result = []
        if not isinstance(string, unicode):
            string = string.decode("utf-8")
        en = ''
        for char in string:
            key = '%X' % ord(char)
            if not self.word_dict.get(key) :
                # 为字母或数字才进入(排除特殊字符)
                if(char.isalpha() == True or char.isdigit() == True) :
                    en += char
                else :
                    # 空格则分割数据
                    if(char.isspace() == True) :
                        result.append(en)
                        en = ''
            else:
                # en有数据则先处理
                if(len(en) > 0) :
                    result.append(en)
                    en = ''
                # 中文转拼音
                result.append(self.word_dict.get(key, char).split()[0][:-1].lower())
        # 防止全是英文或数字
        if(len(en) > 0) :
            result.append(en)
            en = ''

        return result

2.2、hanzi2pinyin_split方法调整

# 原始
    def hanzi2pinyin_split(self, string="", split=""):
        result = self.hanzi2pinyin(string=string)
        if split == "":
            return result
        else:
            return split.join(result)

# 调整后
    def hanzi2pinyin_split(self, string="", split=""):
        return split.join(self.hanzi2pinyin(string=string))

3、调整后的效果

print test.hanzi2pinyin(string='钓鱼岛是hello中国的')
print test.hanzi2pinyin_split(string='钓鱼岛是hello中国world的', split="-")

输出
['diao', 'yu', 'dao', 'shi', 'hello', 'zhong', 'guo', 'de']
diao-yu-dao-shi-hello-zhong-guo-world-de

阅读全文

TOP