1

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

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

我尝试将 + 1 添加到“while index < len(stringToCount)”,但这也无济于事。我对 python 很陌生,我真的不明白我的代码有什么问题。任何帮助,将不胜感激。

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

问题已解决。谢谢你们!

4

6 回答 6

3

看起来您正在使用 Python 2。使用raw_input(...)而不是input(...). input()函数将评估您键入的 Python 表达式,这就是您得到 SyntaxError 的原因。

于 2013-11-07T22:06:37.647 回答
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 
于 2013-11-07T22:15:11.247 回答
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在这里不需要使用 a ,而且非常非 Pythonic imho。尽可能利用使用 Python 等优秀语言的优势,让您的生活更轻松;)

于 2013-11-07T22:11:06.377 回答
1

还,

if stringToCount[index] in vowels:

应该读

if stringToCount[index] in vowelSet:
于 2013-11-07T22:09:53.073 回答
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()方法返回一个字母降低的字符串。它不会修改原始内容:

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

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

在这里你可以很容易地做到:

vowelSet = set("aeiou")

请注意,您也并不严格需要 aset但总的来说它确实更有效。


  # 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"

上面更pythonically写成:

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

# runs the main menu again
getSelection()

不知道你为什么在那里打电话 - 为什么不打电话getSelection()给任何电话runVowel()


希望有帮助!享受学习这门伟大的语言。

于 2013-11-07T22:19:13.597 回答
0

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

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

...请注意,我并没有声称它是最清晰的......只是最快的:)

于 2014-11-11T20:44:32.320 回答