Skip to main content
 首页 » 编程设计

python之针对一组元音测试字符串之Python

2025年05月04日25langtianya

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

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 所说的错误所在,所以我仔细检查了我的代码,在我看来没有任何问题。我是不是通过创建一个集合来测试字符串元素来做这种迂回的方式?有没有更简单的方法来测试字符串元素是否在集合中?

问题已解决。谢谢大家!

请您参考如下方法:

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