在python中,如何在单词中找到元音?

时间:2013-06-06 20:17:41

标签: python

我正在努力建立语言翻译。在python中我的简单任务。或者我想。如果你不知道,那么语言就是你在每个元音之前加上一个单词并说出来的时候。例如,安德鲁将是Upandrupew。我试图找出如何找到用户提交的所有元音,并在他们面前提出。有没有办法在所有元音之前剪掉一个单词。如此优秀将是最好的?感谢。

11 个答案:

答案 0 :(得分:5)

也许

VOWELS = 'aeiou'
def up_it(word):
    letters = []
    for letter in word:
        if letter.lower() in VOWELS:
            letters.append('Up')
        letters.append(letter)
    return ''.join(letters)

可以简化为

def up_it(word):
    return ''.join('up'+c if c.lower() in 'aeiou' else c for c in word)

答案 1 :(得分:4)

你可以用正则表达式来做到这一点:

import re
a = "Hello World."
b = re.sub("(?i)([aeiou])", "up\\1", a)

(?i)使其不区分大小写。 \\1指的是([aeiou])内匹配的字符。

答案 2 :(得分:0)

for vowel in [“a“,“e“,“i“,“o“,“u“]:
    Word = Word.replace(vowel,“up“+vowel)
print(Word)

答案 3 :(得分:0)

import re
sentence = "whatever"
q = re.sub(r"([aieou])", r"up\1", sentence, flags=re.I)

答案 4 :(得分:0)

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

def upped_word(word):
    output = ''
    for character in word:
        if character.lower() in vowels:
            output += "up"
        output += character
    return output

答案 5 :(得分:0)

''.join(['up' + v if v.lower() in 'aeiou' else v for v in phrase])

答案 6 :(得分:0)

这是整个问题的单行

>>> "".join(('up' + x if x.upper() in 'AEIOU' else x for x in 'andrew'))
'upandrupew'

答案 7 :(得分:0)

这是一种做法。

wordList = list(string.lower())

wordList2 = []

for letter in wordList:
    if letter in 'aeiou':
        upLetter = "up" + letter
        wordList2.append(upLetter)
    else:
        wordList2.append(letter)

"".join(wordList2)

创建一个字母列表(wordList),遍历这些字母并将其附加到第二个列表中,该列表最后会加入。

返回:

10: 'upandrupew'

在一行中:

"".join(list("up"+letter if letter in "aeiou" else letter for letter in list(string.lower())))

答案 8 :(得分:0)

我可能会使用RegExp,但已经有很多使用它的答案。我的第二个选择是地图功能,女巫更好然后遍历每个字母。

>>> vowels = 'aeiou'
>>> text = 'this is a test'
>>> ''.join(map(lambda x: 'up%s'%x if x in vowels else x, text))
'thupis upis upa tupest'
>>> 

答案 9 :(得分:0)

def is_vowel(word):
    ''' Check if `word` is vowel, returns bool. '''
    # Split word in two equals parts
    if len(word) % 2 == 0:
        parts = [word[0:len(word)/2], word[len(word)/2:]]
    else:
        parts = [word[0:len(word)/2], word[(len(word)/2)+1:]]

    # Check if first part and reverse second part are same.
    if parts[0] == parts[1][::-1]:
        return True
    else:
        return False

答案 10 :(得分:0)

这是一个聪明的解决方案,可帮助您计算和查找输入字符串中的元音:

name = input("Name:- ")
counter = []
list(name)

for i in name:                 #It will check every alphabet in your string
    if i in ['a','e','i','o','u']:  # Math vowels to your string
        print(i,"  This is a vowel")
        counter.append(i)      # If he finds vowels then he adds that vowel in empty counter
    else:
        print(i)

print("\n")
print("Total no of words in your name ")
print(len(name))

print("Total no of vowels in your name ")
print(len(counter))