簡體   English   中英

查找所有元音的單詞數

[英]Finding the number of words with all vowels

我得到一個存儲在名為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。

只需測試您的任何單詞是否是元音組的子集:

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

假設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

@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()討論: Python中的“ exists”關鍵字?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM