识别一段由字母组成的字符串是拼音还是英文单词

环境:win10 python3.6

先说一下算法思想:

首先建立本地拼音库(不带声调)。使用贪婪算法将字符串从左向右扫描,将字符串与本地拼音库进行匹配,当发现匹配成功时继续扫描,直到又变得不匹配或者遇到结尾为止。

下面是python代码:

def pinyin_or_word(string):
    '''
    judge a string is a pinyin or a english word.
    pinyin_Lib comes from a txt file.
    '''
    string = string.lower()
    stringlen = len(string)
    temp_result = []
    temp_result_len = []
    while True:
        i_list = []
        for i in range(1,stringlen+1):
            if string[0:i] in pinyin_Lib:
                i_list.append(i)
        if len(i_list) == 0:
            print("这是一个英语单词!")
            temp_result = []
            break
        else:
            temp = max(i_list)
            temp_result.append(string[0:temp])
            temp_result_len.append(len(string[0:temp]))
            string = string.replace(string[0:temp],'')
            stringlen = len(string)
            if stringlen == 0:
                print("这是一个拼音!")
                print(temp_result)
                break
    return temp_result,temp_result_len

In [1]: pinyin_or_word("woaizhongguo")
Out[1]: (['wo', 'ai', 'zhong', 'guo'], [2, 2, 5, 3])

这里我封装成了一个函数:传参为字符串,输出“拼音+拼音长度”或者判定英文。

其实这个算法是有缺陷的:

①比如你输入一个英文单词'open',将返回拼音'o'+'pen'

②虽说是判断拼音或单词,但是主要应该说是判断拼音,不能严格判断单词,想要精确判断,需添加单词库。

关于第二点这个容易修复,第一点暂时想不到,倘若哪位大侠可以想到,还望指教。

猜你喜欢

转载自www.cnblogs.com/aloiswei/p/8976596.html