2015-09-20 46 views
0

我已經在腳本中定義了元音。接下來我希望能夠加入輔音和元音在一起,在Python中加入輔音和元音

例如:

如果輔音如下元音,我希望把它一起在一個列表,這個詞的部分和組。

如果我有單詞「房子」我希望能夠在列表中有一個輸出像

['h', 'ous', 'e] 

所以它是我首先應該分開字

['h', 'o', 'u', 's', 'e'] 

和那麼擔心把它們加在一起,或者什麼是最好的方法?

我正在考慮使用一段時間或for循環。

+2

你能告訴我們你現在的代碼? – Atsch

+0

好的,然後使用你覺得你很舒服的循環,並做一些編碼。如果您在代碼中遇到問題,當然需要使用代碼部分,請務必提出疑問。 –

+0

你打算使用正則表達式解決方案嗎? –

回答

0

我認爲這個功能確實你需要:

vowels = ['a', 'e', 'i', 'o', 'u'] 
consonants = ['b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'y', 'z'] 

def group_vowels(string): 
    output = [] 
    substring = '' 
    # Loop through each character in the string 
    for i, c in enumerate(string, start=1): 
     # If it's a consonant, add it to the current substring 
     # and then add the substring to the output list 
     if c in consonants: 
      substring = substring + c 
      output.append(substring) 
      substring = '' 
     # If it's a vowel, add it to the current substring 
     if c in vowels: 
      substring = substring + c 
      # If the word ends with vowels, add them to the output list 
      if i == len(string): output.append(substring) 
    return output 

print group_vowels('house') # ['h', 'ous', 'e'] 
print group_vowels('ouagadougou') # ['ouag', 'ad', 'oug', 'ou'] 

由於J.F.塞巴斯蒂安評論說,你可能要擴大vowelsconsonants名單。

+0

你在第二個例子中缺少一些輸出,最後應該是'ou' –

+0

謝謝 - 修正它。 –

+0

你也可以爲0(1)查找製作元音和輔音集 –

0

幾個例子會有所幫助,但下面的方法似乎與當前的示例工作爲house

print [g for g in re.split(r'([aeiou]+?[^aeiou]+?)', 'house', flags=re.I) if g] 

這顯示:

['h', 'ous', 'e'] 
相關問題