码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2018-05-01 20:23:12      阅读:610      评论:0      收藏:0      [点我收藏+]

标签:建立   []   word   file   def   class   ring   英文单词   修复   

环境: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)
    result = []
    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)
            result.append(string[0:temp])
            string = string.replace(string[0:temp],‘‘)
            stringlen = len(string)
            if stringlen == 0:
#                print("这是一个拼音!")
#                print(result)
                break
    return result

In [1]: pinyin_or_word("woaizhongguo")
Out[1]: [‘wo‘, ‘ai‘, ‘zhong‘, ‘guo‘]

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

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

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

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

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

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

标签:建立   []   word   file   def   class   ring   英文单词   修复   

原文地址:https://www.cnblogs.com/aloiswei/p/8976596.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!