2014-09-27 109 views
2

現在我正在嘗試創建一個oppish翻譯器。也就是說,在一個輔音或幾個輔音連續之後,你給這些字母加上'op'。作爲一個例子,牛會成爲copowop或街道,這將成爲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 

我不知道我做錯了,我試着去通過一個可視化,但無濟於事。所有幫助表示讚賞! :)

+0

那麼一個你'i'在輔音列表 – bwegs 2014-09-27 15:33:50

+0

如何你的意思是?我不應該使用'我'來檢查輔音索引,然後將它們追加到我創建的新列表中? – 2014-09-27 15:35:31

+0

@JohnathanScott:''我''是字符串'我'。它與你的'i'變量沒有關係。你期望'phrase_List [i] == phrase_List [1]'做什麼? – Blender 2014-09-27 15:37:09

回答

0

我認爲問題在於你對問題的處理方法。 嘗試做這樣的事情:

編輯:雖然有一個在這個問題上更好(Python的)答案(感謝端午),這其中並不需要額外的庫

vowels = ['a', 'e', 'i', 'o', 'u'] 

def oppish(word): 
    result = [] 
    first = True 
    prev_vowel = False 

    for letter in list(word): 
     if (letter in vowels) and (not first) and (not prev_vowel): 
      result.append('op') 
      prev_vowel = True 
     else: 
      prev_vowel = False 

     result.append(letter) 
     first = False 
     if not prev_vowel: 
      result.append('op') 
     print ''.join(result) 


oppish('street') 

#> stropeetop 

提示:不要浪費你的時間定義元音和輔音。實際上,有元音和非元音

2

這非常適合itertools.groupby,它可以讓你使用鍵功能在迭代中分組項目。該組將積累,直到鍵功能的返回值發生變化,此時group將產生鍵函數的返回值,以及累積組上的迭代器。在這種情況下,如果一個字母是元音,我們希望我們的關鍵函數返回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 
相關問題