pythoncountcpu-wordparagraph

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()
        #MISSING CODE

    timer = threading.Timer(10.0, yyy) 
    timer.start()
    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


Solution

  • 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
            break
    

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