找出一个单词中的一半字母是元音

时间:2014-10-24 00:57:51

标签: python python-3.x

就像标题所说,我试图找出元音是否至少是单词中字母数量的一半。

继承我的代码:

def mostlyVowels(words):
    vowel = 'aAeEiIoOuU'
    words.split()
    ans =  []
    for word in words:
        for letter in word:
            isvowel = 0
            if letter in vowel:
                isvowel += 1
        if isvowel > ((len(word))/2):
            ans.append(word)
    return ans

# call mostlyvowels
words = 'Our lives begin to end the day we become silent about things that matter'
print(mostlyVowels(words))

所以我应该得到的是['我们的','关于']但是我得到了这个:

['O', 'u', 'i', 'e', 'e', 'i', 'o', 'e', 'e', 'a', 'e', 'e', 'o', 'e', 'i', 'e', 'a', 'o', 'u', 'i', 'a', 'a', 'e']

感谢您抽出宝贵时间提供帮助

8 个答案:

答案 0 :(得分:3)

您自己的代码正在为单词中的每个字母重置isvowel为零,在第二个for循环之前设置isvowel = 0不是之后或者您可以使用sum来缩短代码:

def mostlyVowels(words):
    vowel = {"A","e","E","i","I","o","O","u","U"}
    final = []
    for word in words.split():
        if sum(x in vowel for x in word) >= len(word)/2:
            final.append(word)
    return final

答案 1 :(得分:2)

我实际上建议在不使用除法的情况下这样做,如果只是作为对自动机理论类的致敬,我必须采用模拟使用磁带来跟踪符号:

def mostlyVowels(words):
  acc = []
  for word in words.split():
    i = 0
    for char in word.lower():
      if char in 'aeiou': i += 1
      else:               i -= 1
    if i > 0: acc.append(word)
  return acc

非元音只会减少单词的“大部分 - 元音”,阈值为1或更高:P

答案 2 :(得分:2)

只是为了好玩,这里的Darren Ringer的算法使用列表(in)理解转换成单行:

#! /usr/bin/env python

def mostlyVowels(words):
    return [w for w in words.split() if sum((-1, 1)[c in 'aeiou'] for c in w.lower()) >= 0]


def main():
    words = 'Our lives begin to end the day we become silent about things that matter'
    print(mostlyVowels(words))


if __name__ == '__main__':
    main()

<强>输出

['Our', 'to', 'we', 'become', 'about']

根据问题,我修改了测试,使其包含至少一半字母为元音的单词。

答案 3 :(得分:2)

s = 'Our lives begin to end the day we become silent about things that matter'
words = s.split() # get whitespace-separated words
print([w for w in words if is_vowel_word(w)]) # result

is_vowel_word()可以是:

def is_vowel_word(word, vowels=set('aeiou')):
    """Whether half of the letters in a word are vowels."""
    letters = set(word.lower()) # count each distinct letter in the word once
    return len(vowels & letters) >= len(letters - vowels)

输出

['Our', 'to', 'we', 'about']

或者我们也计算单词中的重复字母:

def is_vowel_word_dups(word, vowels='aeiou'):
    """Whether half of the letters (counting duplicates) in a word are vowels.

    """
    return 2*sum(c in vowels for c in word.lower()) >= len(word)

输出

['Our', 'to', 'we', 'become', 'about']

注意:后一个列表中包含'become'e,其中2出现两次:单词有3个独特元音('eo')和'aeiou'辅音('bcm' )这就是为什么它不包含在第一个列表中。

这是一个有趣的版本,用一个单词来计算元音声音而不是硬编码#!/usr/bin/env python from nltk.corpus import cmudict # $ pip install nltk # $ python -c "import nltk; nltk.download('cmudict')" def is_vowel_word_snd(word, pronunciations=cmudict.dict()): """Whether a word pronunciation contains at least half vowel *sounds*.""" # check all pronuncations of the word return any(2*sum(syl[-1].isdigit() for syl in syllables) >= len(syllables) for syllables in pronunciations.get(word.lower(), [])) s = 'Our lives begin to end the day we become silent about things that matter' words = s.split() # get whitespace-separated words print([w for w in words if is_vowel_word_snd(w)]) 字母:

['Our', 'to', 'the', 'day', 'we', 'about', 'matter']

输出

{{1}}

答案 4 :(得分:1)

words.split()不会修改变量words - 它只返回一个列表,因此您需要将其分配给中间变量。或者你可以跳过中间人并在你的for循环中调用它:

vowel = 'aAeEiIoOuU'
ans = []
for word in words.split():
    # etc.

其次,在你的第二个for循环中,你每次都将isvowel重置为0,所以它永远不会大于1.你应该将该赋值移到循环体之外:

    isvowel = 0
    for letter in word:
        if letter in vowel:
            isvowel += 1
    if isvowel > ((len(word))/2):
        ans.append(word)
    # etc.

答案 5 :(得分:0)

这是因为你需要拆分字符串Words。否则,你只是迭代单词中的每个字符:)

for words in word.split()

可能还有其他问题需要解决,如果您需要进一步的帮助,请与我们联系。

答案 6 :(得分:0)

def mostly_vowels(words):
    vowels = set('aeiouAEIOU')
    for word in words.split():
        v = 0
        for char in word:
            if char in vowels:
                v += 1
        if v >= len(word)/2:
            print(word)

答案 7 :(得分:0)

有一些好的答案指出了这个问题。但是,你可以使用List理解来做到这一点。尝试运行此代码:

vowel = 'aAeEiIoOuU'
words = 'Our lives begin to end the day we become silent about things that matter'
wordsList= words.split(" ")

l= [([x for x in item if x in list(vowel)], len(item), item) for item in  wordsList]
b= [y for y in l if (y[1]//2<len(y[0])) ]
print [z[2] for z in b]

输出: [&#39;我们的&#39;,&#39;关于&#39;]