HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

Word counter script

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
scriptwordcounter

Problem

I made a word counter. It works as long as there aren't any lone punctuation marks. How could it be improved? (Could it be made simpler? Are the comments detailed/clear enough? etc.) I know it's simple, but I don't want to develop bad habits early on.

#prompt user to input a sentence
toCount = raw_input("--- ")

#function that counts words of inputted sentence
def countWords(theString):

    stringLength = len(theString)

    #index for each character in string
    counter1 = 0

    #stores word count
    accumulator = 0

    #go through each character in input text. if a character is a space
    #with no preceding spaces, add 1 to word count.
    while counter1  0 and theString[counter1 - 1] != ' ':
            accumulator = accumulator + 1
            counter1 = counter1 + 1
        else:
            counter1 = counter1 + 1

    #if last character in input text is not a space, add 1 to word count
    if theString[counter1 - 1] != ' ':
        accumulator = accumulator + 1

    output = "You typed " + str(accumulator) + " words."

    return output

print countWords(toCount)

Solution

Here's one way to simplify it:

inp = raw_input("--- ")

print len(inp.split())


I'm not sure if you were unaware of this or if you were reinventing-the-wheel.

Before I go all out, maybe you could comment or leave an edit on your question letting us know if you meant to reinvent things here.

Code Snippets

inp = raw_input("--- ")

print len(inp.split())

Context

StackExchange Code Review Q#54254, answer score: 6

Revisions (0)

No revisions yet.