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

标签 python string set element

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

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 的原因。

关于python - 针对一组元音测试字符串 - Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19847630/

相关文章:

c++ - 基于两个集合的类的自定义迭代器

MySQL 字符串中多次出现相同的字母

C# get、set访问器与数组结合【system.null引用异常】

python - 在 Django 中,我如何执行服务器端功能并在客户端监控进度

python - 尝试将列表条目添加到字符串时出现 "TypeError: can only join an iterable"

java - 将字符串修改应用于数组/列表

c - 将两根绳子放在一起

vba - 有没有更有效的方法来计算数组的幂集?

python - MapReduce:使用Mrjob在网络图中查找三角形

python - 在 NumPy 中向量化向量矩阵乘法