2012-09-23 36 views
0

我想在某些詞的元音(即不是像即連續的元音或EI),例如添加文本:如何解決Python中的這個字符串問題?

字:「奇怪」

文本元音前補充:「IB」

結果: 'wibeird'

因此文本 'IB' 元音 'e' 的前加入。請注意,它並沒有用'ib'代替'i',因爲當元音連續時,我不希望它添加文本。

然而,當我這樣做:

字: '狗'

文本元音前補充: 'OB'

結果: 'doboog'

正確的結果應該是:'dobog'

我一直在試圖調試我的程序,但我似乎無法弄清楚邏輯,以確保它能正確打印'wibeird'和'dobog'。

這是我的代碼,用'ob'代替first_syl,用'怪狗'先運行後用'dog'代替。

first_syl = 'ib' 
word = 'weird' 

vowels = "aeiouAEIOU" 
diction = "bcdfghjklmnpqrstvwxyz" 
empty_str = "" 
word_str = "" 
ch_str = "" 
first_vowel_count = True 

for ch in word: 
    if ch in diction: 
     word_str += ch 
    if ch in vowels and first_vowel_count == True: 
     empty_str += word_str + first_syl + ch 
     word_str = "" 
     first_vowel_count = False 
    if ch in vowels and first_vowel_count == False: 
     ch_str = ch 
    if word[-1] not in vowels: 
     final_str = empty_str + ch_str + word_str 

print (final_str) 

我正在使用Python 3.2.3。另外我不想使用任何導入的模塊,試圖這樣做來理解python中字符串和循環的基礎知識。

+0

請注意,您不是替換元音,而是在元音前插入一個字符串。如果我們將其替換,'dog'將會在'ob'替換'o'後變成'dobg'。 –

+0

在你的第一個例子中,它看起來並不像你完全替換了「e」 - 還有一個「wibeird」中的e –

+0

對不起,我不是故意要'替換'我實際上是想在元音之前添加文本, 我道歉。我現在在說明中解決了這個問題。 – Goose

回答

1

不必使用正則表達式,當你不必。有一個名言時遇到一個問題是去

有些人,覺得 「我知道,我將使用正則表達式。」現在他們有兩個問題。

這可以很容易地用基本的if-then語句來解決。這裏有一個解釋正在使用的邏輯的註釋版本:

first_syl = 'ib' # the characters to be added 
word = 'dOg'  # the input word 

vowels = "aeiou" # instead of a long list of possibilities, we'll use the 
       # <string>.lower() func. It returns the lowercase equivalent of a 
       # string object. 
first_vowel_count = True # This will tell us if the iterator is at the first vowel 
final_str = ""   # The output. 

for ch in word: 
    if ch.lower() not in vowels:  # If we're at a consonant, 
     first_vowel_count = True  # the next vowel to appear must be the first in 
            # the series. 

    elif first_vowel_count:   # So the previous "if" statement was false. We're 
            # at a vowel. This is also the first vowel in the 
            # series. This means that before appending the vowel 
            # to output, 

     final_str += first_syl  # we need to first append the vowel- 
            # predecessor string, or 'ib' in this case. 
     first_vowel_count = False # Additionally, any vowels following this one cannot 
            # be the first in the series. 

    final_str += ch     # Finally, we'll append the input character to the 
            # output. 
print(final_str)      # "dibOg" 
+0

我喜歡那句話,哇,你一定是個天才,我顯然是過於複雜的東西,學習這對我來說很難,但卻讓人着迷。有沒有辦法在這個網站給你發信息,我可能還有幾個問題,因爲我打算接下來要做的是在第一個元音之後加上每個元音,並在它之前添加不同的文本集合(如second_syl,third_syl等)? – Goose

+0

@ Ratman2050沒有辦法發送私人信息;這個評論系統是非常私密的。如果你有更多的問題,隨時爲他們提供更多的帖子,我相信你會得到同樣有用的反饋 – jsvk

2

您是否考慮過正則表達式?

import re 

print (re.sub(r'(?<![aeiou])[aeiou]', r'ib\g<0>', 'weird')) #wibeird 
print (re.sub(r'(?<![aeiou])[aeiou]', r'ob\g<0>', 'dog')) #dobog 
+0

對不起,我沒有提到這一點,我寧願不使用導入的模塊和正則表達式,試圖做到這一點,以瞭解Python中的字符串和循環的基礎..謝謝。 – Goose