检查单词,python中元音的存在

时间:2014-02-17 06:26:45

标签: python string for-loop

我需要检查一个单词中是否存在元音。如果是,则应对单词op op(word)执行操作。我想避免for循环因为我想到了这个:

for char in word:
    if char in 'aeiou':
#confused here... 

请推荐一种在执行时间方面成本低廉的方法。也帮助我纠正上述方法。

6 个答案:

答案 0 :(得分:5)

vowels = {"a", "e", "i", "o", "u", "A", "E", "I", "O", "U"}
if any(char in vowels for char in word):
   ...

注意:这更好,因为它会在找到单词中的元音后立即短路。因此,除非字符串中没有元音,否则不必检查所有字符。

修改:选择timeit test,发现@falsetru's answer速度非常快,但优化程度很低,re版本优于其他所有内容。

import re

vowels = {"a", "e", "i", "o", "u", "A", "E", "I", "O", "U"}
pattern = re.compile("[AEIOUaeiou]")

def intersection():
    return bool(vowels.intersection("TWYNDYLLYNGS"))

def any_version():
    return any(char in vowels for char in "TWYNDYLLYNGS")

def re_version():
    return bool(pattern.search("TWYNDYLLYNGS"))

def disjoint():
    return vowels.isdisjoint("TWYNDYLLYNGS")

from timeit import timeit

print timeit("intersection()", "from __main__ import intersection, vowels")
print timeit("any_version()", "from __main__ import any_version, vowels")
print timeit("re_version()", "from __main__ import re_version, vowels")
print timeit("disjoint()", "from __main__ import disjoint, vowels")

答案 1 :(得分:4)

您可以使用set intersection

来避免for循环
if set('aeiou').intersection(word.lower()):

答案 2 :(得分:3)

使用set.isdisjoint(此方法在找到匹配后立即返回):

>>> vowels = set('aeiou') # set('aeiouAEIOU') if you want case-insensitivty
>>> not vowels.isdisjoint('bcd')
False
>>> not vowels.isdisjoint('hello')
True

答案 3 :(得分:0)

你可以使用正则表达式。

import re

if re.search('[AEIOU]', word, flags=re.I):
    # contains vowels
else:
    # does not

答案 4 :(得分:0)

def vowelz(a):
        vowels = ["a", "e", "i", "o", "u"]
        vowel = False
        for vowell in vowels:
                if vowell in a:
                        vowel = True
        print vowel
vowelz(raw_input("Enter a word:"))

答案 5 :(得分:0)

或者您可以这样做。非常简单。

line = input('Enter text: ')
frequency = {'a': 0, 'e': 0, 'i': 0, 'o': 0, 'u': 0}
for i in line:
    if i in 'aeiou':
        frequency[character] = frequency[character] + 1
for vowel in 'aeiou':
    print(vowel + ': ' + str(frequency[vowel]))