测试一组元音的字符串 - Python

时间:2013-11-07 22:04:44

标签: python string set elements

这是我程序中的一个模块:

def runVowels():
      # explains what this program does
    print "This program will count how many vowels and consonants are"
    print "in a string."
      # get the string to be analyzed from user
    stringToCount = input("Please enter a string: ")
      # convert string to all lowercase letters
    stringToCount.lower()
      # sets the index count to it's first number
    index = 0
      # a set of lowercase vowels each element will be tested against
    vowelSet = set(['a','e','i','o','u'])
      # sets the vowel count to 0
    vowels = 0
      # sets the consonant count to 0
    consonants = 0
      # sets the loop to run as many times as there are characters
      # in the string
    while index < len(stringToCount):
          # if an element in the string is in the vowels
        if stringToCount[index] in vowels:
              # then add 1 to the vowel count
            vowels += 1
            index += 1
        # otherwise, add 1 to the consonant count
        elif stringToCount[index] != vowels:
            consonants += 1
            index += 1
          # any other entry is invalid
        else:
            print "Your entry should only include letters."
            getSelection()

      # prints results
    print "In your string, there are:"
    print " " + str(vowels) + " vowels"
    print " " + str(consonants) + " consonants"
      # runs the main menu again
    getSelection()

然而,当我测试这个程序时,我收到了这个错误:

line 28, in runVowels
    stringToCount = input("Please enter a string: ")
  File "<string>", line 1
    PupEman dABest
                 ^
SyntaxError: unexpected EOF while parsing

我尝试在“while index&lt; len(stringToCount)”中添加+ 1,但这也无济于事。我是python的新手,我真的不明白我的代码有什么问题。任何帮助将不胜感激。

我研究了这个错误,我发现只有EOF代表文件的结尾。这对解决我的问题毫无帮助。此外,我知道有时错误不一定是python说错误的地方,所以我仔细检查了我的代码,在我的眼中似乎没有任何错误。我是通过创建一个测试字符串元素的集合来实现这种方式的吗?有没有更简单的方法来测试字符串元素是否在一个集合中?

问题已解决。谢谢大家!

6 个答案:

答案 0 :(得分:3)

看起来你正在使用Python 2. Use raw_input(...)而不是input(...)The input() function将评估您输入的Python表达式,这就是您获得SyntaxError的原因。

答案 1 :(得分:2)

建议使用raw_input。你也不需要这样做:

while index < len(stringToCount):
      # if an element in the string is in the vowels
    if stringToCount[index] in vowels:
          # then add 1 to the vowel count
        vowels += 1
        index += 1
    # otherwise, add 1 to the consonant count
    elif stringToCount[index] != vowels:
        consonants += 1
        index += 1
      # any other entry is invalid
    else:
        print "Your entry should only include letters."
        getSelection()

Python中的字符串是可迭代的,所以你可以这样做:

for character in stringToCount:
    if character in vowelSet : # Careful with variable names, one is a list and one an integer, same for consonants.
        vowels += 1
    elif character in consonantsSet: # Need this, if something is not in vowels it could be a number.
         consonants += 1
    else:
        print "Your entry should only include letters."

这应该没问题。此处不需要使用while,非Pythonic imho。使用像Python这样的好语言的优势,可以让你的生活更轻松;)

答案 2 :(得分:2)

你可以像这样计算元音:

>>> st='Testing string against a set of vowels - Python'
>>> sum(1 for c in st if c.lower() in 'aeiou')             
12

你可以为辅音做类似的事情:

>>> sum(1 for c in st if c.lower() in 'bcdfghjklmnpqrstvwxyz')    
26 

答案 3 :(得分:1)

此外,

if stringToCount[index] in vowels:

应该阅读

if stringToCount[index] in vowelSet:

答案 4 :(得分:1)

这是另一种可以解决同样问题的方法:

def count_vowels_consonants(s):
    return (sum(1 for c in s if c.lower() in "aeiou"),
            sum(1 for c in s if c.lower() in "bcdfghjklmnpqrstvwxyz"))

即便:

>>> count_vowels_consonants("aeiou aeiou yyy")
(10, 3)
>>> count_vowels_consonants("hello there")
(4, 6)

Python真的很棒。


文件中的错误运行如下(加上一些建议):

stringToCount = input("Please enter a string: ")

如果您想要用户输入的字符串,那么这应该是raw_input


stringToCount.lower()

.lower()方法返回 new 字符串,其字母已降低。它不会修改原文:

>>> a = "HELLO"
>>> a.lower()
"hello"
>>> a
"HELLO"

vowelSet = set(['a','e','i','o','u'])

在这里你可以轻松地做到:

vowelSet = set("aeiou")

请注意,您也不需要set,但一般来说确实更有效率。


  # sets the vowel count to 0
vowels = 0
  # sets the consonant count to 0
consonants = 0

请您不要对这些简单的陈述发表评论。


index = 0
while index < len(stringToCount):

你通常不需要在python中使用这样的while循环。请注意,您使用index的所有内容都是获取stringToCount中的相应字符。应该是:

for c in stringToCount:

现在而不是:

    if stringToCount[index] in vowels:
        vowels += 1
        index += 1

你这样做:

    if c in vowels:
        vowels += 1

    elif stringToCount[index] != vowels:
        consonants += 1
        index += 1
      # any other entry is invalid

不太对劲。你正在检查一个角色不等于一组。也许你的意思是:

    elif c not in vowels:
        consonants += 1

但是那时候没有else案例......在这里修改你的逻辑。


print "In your string, there are:"
print " " + str(vowels) + " vowels"
print " " + str(consonants) + " consonants"

上面的内容更加诡异:

print "In your string, there are: %s vowels %s consonants" % (
    vowels, consonants)

# runs the main menu again
getSelection()

不确定为什么要在那里打电话 - 为什么不从任何电话getSelection()拨打runVowel()


希望有所帮助!喜欢学习这门优秀的语言。

答案 5 :(得分:0)

Bah,所有代码都很慢;)。显然,最快的解决方案是:

slen = len(StringToCount)
vowels = slen - len(StringToCount.translate(None, 'aeiou'))
consonants = slen - vowels

...请注意,我并不认为它是最清晰的 ...只是最快的:)