zoukankan      html  css  js  c++  java
  • python识别一段由字母组成的字符串是否是拼音

    环境:win10 python3.6

    先说一下算法思想:
    首先建立本地拼音库(不带声调)。使用逆向最大匹配将字符串与本地拼音库(这里提供给大家一个)进行匹配。话不多说,见code:

    def pinyin_or_word(string):
        '''
        judge a string is a pinyin or not.
        pinyinLib comes from a txt file.
        '''
        max_len = 6   # 拼音最长为6
        string = string.lower()
        stringlen = len(string)
        result = []
        while True:
            matched = 0
            matched_word = ''
            if stringlen < max_len:
                max_len = stringlen                
            for i in range(max_len, 0, -1):
                s = string[(stringlen-i):stringlen]
                if s in pinyinLib:
                    matched_word = s
                    matched = i
                    break
            if len(matched_word) == 0:
                break
            else:
                result.append(s)
                string = string[:(stringlen-matched)]
                stringlen = len(string)
                if stringlen == 0:
                    break
        return result
    
    In [1]: pinyin_or_word("woaizhongguo")
    Out[1]: ['wo', 'ai', 'zhong', 'guo']
    

    其实这个算法是有缺陷的:比如你输入一个英文单词'open',将返回拼音'o'+'pen'。
    注:正向最大匹配会遇到“xiange”分成“xiang/e”的情况。

  • 相关阅读:
    反射和内置方法重写
    封装
    接口与抽象类 、多态
    面向对象--继承和组合
    python对象
    模块导入
    python序列化模块
    time random sys os 模块
    python re模块和collections
    python各种推导式
  • 原文地址:https://www.cnblogs.com/aloiswei/p/8976596.html
Copyright © 2011-2022 走看看