Skip to main content
 首页 » 编程设计

python之如何将字符串附加到列表中的辅音

2024年10月25日22luoye11

现在我正在尝试创建一个 oppish 翻译器。也就是说,在一个辅音或连续几个辅音之后,您可以在这些字母上添加“op”。例如,cow 会变成 copowop 或 street 会变成 stropeetop。这是我目前所拥有的:

def oppish(phrase): #with this function I'm going to append 'op' or 'Op' to a string. 
    consonants =  ['b','c','d','f','g','h','i','j','k','l','m','n','p','q','r','s','t','v','w','x','y','z'] 
    vowels = ['a', 'e', 'i', 'o', 'u'] #this and the preceding line create a variable for the vowels we will be looking to append 'op' to.     
    if phrase == '':    #error case. if the input is nothing then the program will return False. 
        return False 
    phrase_List = list(' ' + phrase) # turns the input phrase into a list which allows for an        index to search for consonants later on. 
    new_phrase_List = list() #creates new list for oppish translation 
    for i in range(1, len(phrase_List)): 
        if phrase_List[i] == phrase_List[1]: 
            new_phrase_List.append(phrase_List[i]) 
        elif phrase_List[i] in consonants: 
            new_phrase_List.append('op') #adds op to the end of a consonant within the list and then appends it to the newlist 
        new_phrase_List.append(phrase_List[i]) #if the indexed letter is not a consonant it is appended to the new_phrase_list. 
    print 'Translation: ' + ''.join(new_phrase_List) 
 
oppish('street') 

这里唯一的问题是上面的代码产生了这个

Translation: ssoptopreeopt 

我不确定我做错了什么,我试过通过可视化工具但无济于事。感谢所有帮助! :)

请您参考如下方法:

这非常适合 itertools.groupby ,这将使您可以使用键函数将项目分组到可迭代对象中。该组将累积直到键函数的返回值发生变化,此时 group by 将产生键函数的返回值和累积组的迭代器。在这种情况下,如果字母是元音,我们希望我们的键函数返回 True。这样,我们将从 groupby 返回连续辅音组和连续元音组:

from itertools import groupby 
 
vowels = {'a', 'e', 'i', 'o', 'u'}  # set instead of list, because lookups are O(1) 
 
def oppish(phrase): 
    if not phrase: 
        return False 
 
    out  = [] 
    for is_vowel, letters in groupby(phrase, lambda x: x in vowels): 
        out.append(''.join(list(letters))) 
        if not is_vowel: 
            out.append('op') 
    return ''.join(out) 
 
 
print oppish('street') 
print oppish('cow') 

输出:

stropeetop 
copowop