سؤال

This is a module in my program:

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

However, when I test this program, I get this error:

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

I tried adding a + 1 to the "while index < len(stringToCount)" but that didn't help either. I'm pretty new to python and I don't really understand what's wrong with my code. Any help would be appreciated.

I researched this error, all I found out was that EOF stands for end of file. This didn't help at all with resolving my problem. Also, I understand that sometimes the error isn't necessarily where python says the error is, so I double-checked my code and nothing seemed wrong in my eyes. Am I doing this the round-about way by creating a set to test the string elements against? Is there a simpler way to test if string elements are in a set?

Question resolved. Thank you to all!

هل كانت مفيدة؟

المحلول 2

As suggested use raw_input. Also you don't need to do this:

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

Strings in Python are iterable, so you can just do something like this:

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

This should do just fine. Using a while is not necessary here, and very non-Pythonic imho. Use the advantage of using a nice language like Python when you can to make your life easier ;)

نصائح أخرى

Looks like you're using Python 2. Use raw_input(...) instead of input(...). The input() function will evaluate what you have typed as a Python expression, which is the reason you've got a SyntaxError.

You can count the vowels like so:

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

You can do something similar for consonants:

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

Also,

if stringToCount[index] in vowels:

should read

if stringToCount[index] in vowelSet:

Here's another way you could solve the same thing:

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

To wit:

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

Python truly is grand.


The errors in your file run as follows (plus some suggestions):

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

This should be raw_input if you want what the user typed in as a string.


stringToCount.lower()

The .lower() method returns a new string with its letters lowered. It doesn't modify the original:

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

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

Here you could just as easily do:

vowelSet = set("aeiou")

Note you also don't strictly need a set but it is indeed more efficient in general.


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

Please, you don't need comments for such simple statements.


index = 0
while index < len(stringToCount):

You usually don't need to use a while loop like this in python. Note that all you use index for is to get the corresponding character in stringToCount. Should instead be:

for c in stringToCount:

Now instead of:

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

You just do:

    if c in vowels:
        vowels += 1

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

Not quite right. You're checking that a character doesn't equal a set. Maybe you meant:

    elif c not in vowels:
        consonants += 1

But then there'd be no else case... Got to fix your logic here.


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

The above is more pythonically written as:

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

# runs the main menu again
getSelection()

Not sure why you're calling that there - why not call getSelection() from whatever calls runVowel()?


Hope that helped! Enjoy learning this great language.

Bah, all that code is so slow ;). Clearly the fastest solution is:

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

...note that I don't claim it's the clearest... just the fastest :)

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top