0

我正在尝试在某些单词中添加带有元音的文本(不是像 ie 或 ei 这样的连续元音),例如:

词:“奇怪”

在元音之前添加的文本:'ib'

结果:'wibeird'

因此,在元音“e”之前添加了文本“ib”。请注意它没有用 'ib' 替换 'i',因为当元音是连续的时,我不希望它添加文本。

但是,当我这样做时:

词:“狗”

在元音之前添加的文本:'ob'

结果:'doboog'

正确的结果应该是:'dobog'

我一直在尝试调试我的程序,但我似乎无法弄清楚逻辑以确保它正确打印“wibeird”和“dobog”。

这是我的代码,先用 'weird.

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中字符串和循环的基础知识。

4

2 回答 2

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
于 2012-09-23T21:31:59.770 回答
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"
于 2012-09-23T23:48:08.617 回答