如何在单词列表中找到元音数量?

时间:2019-04-03 18:53:17

标签: python python-3.x

任务是从列表中找到每个单词中的元音数量,并输出结果字典。

我已经尝试过这种方式:

wordsList = ["creativity", "anna", "civic", "apology", "refer", "mistress", "rotor", "mindset"]
dictionary = {}
vowels = "aeoui"
count = 0

for word in wordsList:
    for letter in word:
        if letter in vowels:
            count = count + 1
            dictionary[word] = (count)

print(dictionary)

这就是我当时的需要,我需要帮助如何具体计算每个单词。提前致谢! 预期输出:

{anna:2} etc.

4 个答案:

答案 0 :(得分:1)

您可以在sum函数中为单词中的每个字母使用生成器表达式和元音测试:

dictionary = {word: sum(letter in 'aeiou' for letter in word) for word in wordsList}

dictionary变为:

{'creativity': 4, 'anna': 2, 'civic': 2, 'apology': 3, 'refer': 2, 'mistress': 2, 'rotor': 2, 'mindset': 2}

答案 1 :(得分:1)

您的错误是计数需要在循环内初始化: 您还可以添加一个部分来计算大写和小写的元音。

wordsList = ["creativity", "anna", "civic", "apology", "refer", "mistress", "rotor", "mindset"]
dictionary = {}
vowels = "aeoui"

for word in wordsList:
    count = 0 # I moved it
    for letter in word:
        if letter.lower() in vowels: # to consider both upper/lower case
            count = count + 1
            dictionary[word] = (count)

print(dictionary)

答案 2 :(得分:0)

尝试一下。您没有在开始检查下一个单词时将计数变量重置为0。我还修复了dictionary[word] = count

的缩进
wordsList = ["creativity", "anna", "civic", "apology", "refer", "mistress", "rotor", "mindset"]
dictionary = {}
vowels = "aeoui"
count = 0

for word in wordsList:
    count = 0
    for letter in word:
        if letter in vowels:
            count = count + 1
    dictionary[word] = count

print(dictionary)
#{'creativity': 4, 'anna': 2, 'civic': 2, 'apology': 3, 'refer': 2, 'mistress': 2, 'rotor': 2, 'mindset': 2}

答案 3 :(得分:0)

通常这样的事情都是通过Python中的理解来完成的。与使用for循环和计数器变量相比,以下是更惯用的Python,并为您分解了步骤。 (它也通过在测试前将单词转换为小写来处理大写字母。)

words = ['creativity', 'SpongbUngulator']

vowel_counts = {}
vowels = set('aeiou')
for word in words:
    lowercase_word = word.lower()
    found_vowels = [letter for letter in lowercase_word if letter in vowels]
    vowel_count = len(found_vowels)
    vowel_counts[word] = vowel_count
print(vowel_counts)

值得指出的是,set(lowercase_word).intersection(vowels)会告诉您每个单词中哪个独特元音。 Python集非常值得了解。