计算包含所有元音的单词数量

0 投票
3 回答
4204 浏览
提问于 2025-04-17 17:04

我有一个文本文件,里面的内容存储在一个叫做 words_list 的列表里:

if __name__ = "__main__":
    words_file = open('words.txt')

    words_list = []
    for w in words_file:
        w = w.strip().strip('\n')
        words_list.append(w)

这个字符串列表看起来是这样的(其实是一个非常非常长的单词列表)

我需要找到“所有包含所有元音的单词”;到目前为止我有:

def all_vowel(words_list):
    count = 0
    for w in words_list:
        if all_five_vowels(w):   # this function just returns true
            count = count + 1
    if count == 0
        print '<None found>'
    else 
        print count

现在的问题是,count 每次看到一个元音就加1,但我想要的是,只有当整个单词都包含所有元音时才加1。

3 个回答

0

@Martijn Peters 已经分享了一个可能是 Python 中最快的解决方案。为了完整性,这里还有另一种不错的 Python 解决方法:

vowels = set('aeiou')

with open('words.txt') as words_file:
    for word in words_file:
        word = word.strip()
        if all(ch in vowels for ch in word):
            print word

这个方法使用了内置的 all() 函数和生成器表达式,这是一个很实用的写法。它的意思是“如果这个单词里的所有字符都是元音字母,就打印这个单词。” Python 还有一个 any() 函数,可以用来检查“如果这个单词里有任何一个字符是元音字母,就打印这个单词”。

关于 any()all() 的更多讨论可以在这里找到: "exists" 关键字在 Python 中?

6

简单测试一下你的单词中是否有任何一个是元音字母集合的子集:

vowels = set('aeiou')

with open('words.txt') as words_file:
    for word in words_file:
        word = word.strip()
        if vowels.issubset(word):
            print word

set.issubset() 可以用于任何序列(包括字符串):

>>> set('aeiou').issubset('word')
False
>>> set('aeiou').issubset('education')
True
3

假设 word_list 这个变量确实是一个列表,那么你可能是把 "all_five_vowels" 这个函数写错了。

这里有一个可能的替代实现方式:

def all_five_vowels(word):
    vowels = ['a','e','o','i','u']
    for letter in word:
        if letter in vowels:
            vowels.remove(letter)
            if len(vowels) == 0:
                return True
    return False

撰写回答