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”的情况。

  • 相关阅读:
    695. 岛屿的最大面积(深搜)
    147. 对链表进行插入排序(排序)
    566. 重塑矩阵(模拟)
    238. 除自身以外数组的乘积(前后缀积)
    29.Java基础_接口
    C++ STL queue
    C++ STL stack
    C++ STL string
    C面向接口编程和C++多态案例
    单例模式入门
  • 原文地址:https://www.cnblogs.com/aloiswei/p/8976596.html
Copyright © 2011-2022 走看看