2013-12-23 74 views
0

我是一名Python初學者。到目前爲止,我得到了這個:單獨的音節創建規則

vowels = 'aeiouAEIUO' 
consonants = 'bcdfghjklmnñpqrstvwxyzBCDFGHJKLMNÑPQRSTVWXYZ' 
a = input('Type a word: ') 

for i in range(len(a)): 
    cont1 = 0 
    cont2 = 0 
    if a[i] in consonants: 
     cont1 = i - 1 
     cont2 = i + 1 
     if a [cont1] in vowels and a [cont2] in vowels: 
       print('consonant between vowels') 

我想分開音節。我想創建一個規則,當一個輔音在2個元音之間時,輔音必須加入到正確的元音並且打印由' - '分隔的音節montoya = mon-to-ya amor = a-mor clase = cla-se

這段代碼當然會給出一個錯誤:IndexError:字符串索引超出範圍。我不知道這意味着什麼。

感謝

+0

的規則是不是很好,但。它不適用於例如「letra」在元音之間有兩個輔音。 – tripleee

+0

這將是另一個規則。有幾條規則我想申請,但我想從兩個元音之間的輔音開始 – user2558831

回答

0

I want to create a rule that when a consonant is between 2 vowels, the consonant has to join to the vowel on it's right.

你可以使用re

>>> import re 
>>> vowels = 'aeiouAEIUO' 
>>> consonants = 'bcdfghjklmnñpqrstvwxyzBCDFGHJKLMNÑPQRSTVWXYZ' 
>>> pattern="([" + vowels + "])" + "([" + consonants + "]" + "[" + vowels + "])" 
>>> re.sub(pattern, r'\1-\2', "amor") 
'a-mor' 
>>> re.sub(pattern, r'\1-\2', "clase") 
'cla-se' 
>>> 
+0

謝謝。但是,我如何在代碼中實現這一點。此外,我試過: >>> re.sub(pattern,r'\ 1- \ 2',「alexis」) 'a-lexis' – user2558831

+0

@ user2558831您的問題並不十分清楚。你能澄清嗎? – devnull