0

i am trying to get the positions of the word the user types in, but I can only find the position if the word only appears once in the sentence, how do I find the position if the inputted word appears multiple times in the sentence?

if varInput in varwords:
    print ("Found word")
    #prints total number of words
    print("The total number of words is: "  + str(len(varwords)))#http://stackoverflow.com/questions/8272358/how-do-i-calculate-the-number-of-times-a-word-occurs-in-a-sentence-python
    #finds out how many times the word occurs in the sentence
    wordOcc = (varwords.count(varInput))
    #if word occurence = 1 then print the position of the word
    if wordOcc ==1:
        pos = varwords.index(varInput)
        pos = pos+1
        print("the word "+varInput+" appears at position:")
        print(pos)

    else if wordOcc =>2:
        pos1 = varwords.index(varInput)
juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172
  • 3
    Have a look here: ["How to find all occurrences of an element in a list?"](http://stackoverflow.com/questions/6294179/how-to-find-all-occurrences-of-an-element-in-a-list) – Ilja Everilä Sep 19 '16 at 09:50

1 Answers1

0

The .index method will only return the first occurrence; it is not an iterator that yields different values.

However, there is a quite easy way to find all of the occurrences. You can run over the indexes of the words array, and add the ones where the item is the specified word:

indexes = [i for i in range(len(sentence)) if sentence[i] == word]

This will return all of the occurrences as a list, or an empty list (with len(indexes)==0) if the word does not happen to be found.

Uriel
  • 15,579
  • 6
  • 25
  • 46