用一组元音Python测试字符串

2024-10-01 15:43:35 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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()

但是,当我测试这个程序时,我得到一个错误:

^{pr2}$

我尝试在“whileindex<;len(stringToCount)”中添加一个+1,但这也没用。我对python还很陌生,我不知道我的代码有什么问题。任何帮助都将不胜感激。在

我研究了这个错误,我发现EOF代表文件结束。这对解决我的问题毫无帮助。另外,我明白有时候错误并不一定是python所说的错误所在,所以我仔细检查了代码,我的眼睛里似乎没有什么错误。我是不是通过创建一个测试字符串元素的集合来实现这一点?有没有更简单的方法来测试字符串元素是否在一个集合中?在

问题已解决。谢谢大家!


Tags: thetoin程序stringindexcount错误
3条回答

你可以这样计算元音:

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

您可以对辅音执行类似的操作:

^{pr2}$

看起来你在用Python2。Use ^{}而不是{}。The ^{} function将计算您键入的Python表达式,这就是您得到SyntaxError的原因。在

建议使用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中的字符串是iterable的,因此您只需执行以下操作:

^{pr2}$

这应该可以。这里不需要使用while,而且非常非Python式的imho。尽可能使用Python这样的好语言,让您的生活更轻松;)

相关问题 更多 >

    热门问题