How to count words in a string in python


I want to be able to input a word and for python to count the number of words up to that word in a previous paragraph.

This is for a program to help you know how much words you can read in one minute. A paragraph is printed and a timer is set up for one minute. When the minute ends, the user inputs the word they reached in the paragraph and the program must tell you how many words you read up to that one.

print ('write start to begin the program')
x = ('')

if x == (''):
    x = input()

if x == 'start':
    import threading 
    def yyy(): 
        print("time is up")
        print('write the last word you read')
        word = input()

    timer = threading.Timer(10.0, yyy) 
    print ('paragraph to read')

this is shortened but I need a function for python to count the words in the paragraph UP TO the one the user inputs once the time is up and to print that number

Asked By: Manuel



You could use split() to split the paragraph string into a list of words:

#paragraph_text = "One two three four"
words = paragraph_text.split(' ')
#words = ["One", "two", "three", "four"]

You could then loop through this list, comparing it to the word the user inputted:

for counter, candidate in enumerate(words):
    if candidate == word:
        print("You have read %s words!" % (counter + 1))
        #Other actions

This is a very simplistic implementation; this will not work if there are duplicate words etc.

Answered By: Brett Warren
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.