Peter
Peter

Reputation: 9

Finding the position of a word in a string with the word repeating

Here's my code:

sentence= input("Enter a sentence")
keyword= input("Input a keyword from the sentence")
words = sentence.split(' ')
if keyword in words:
    pos = words.index(keyword)
    pos = 0+1
    print(pos)

Right, so this is what i have but if the word repeats then it only shows the first position. Any ideas?

Upvotes: 1

Views: 12380

Answers (4)

Killer32c
Killer32c

Reputation: 1

This is how to do the code but with an error message on the end if a word is not in the sentence

 sentence= input("Please Enter A Sentence With No Puncatuation:> ")
 sentence= sentence.lower()
 keyword= input("Please Input A Word From The Sentence:> ")
 keyword= keyword.lower()
 words= sentence.split(' ')
 for (i, subword) in enumerate(words):
     if(subword == keyword):
        print(i+1)
        break
 else:
     print("Error This Word Isnt In The Sentence")

This Code Is Also Case Insensitive So You Can Do it In what ever Case

Upvotes: -1

Ori Nachum
Ori Nachum

Reputation: 598

Try this:

sentence= input("Enter a sentence")
keyword= input("Input a keyword from the sentence")
words = sentence.split(' ')
for (i, subword) in enumerate(words):
    if (subword == keyword): 
        print(i+1)

Upvotes: 2

LetzerWille
LetzerWille

Reputation: 5658

one liner with Counter

from collections import Counter
import re

s = "A sunny day, or rainy day"
# first split. Counter will find frequencies. most_common(1) will
# find repeating word and its frequency (2 in this case). 
# [0][0] will extract the word from Counter tuple, and put it into rindex
# as argument. 
print(s.rindex(Counter(re.split(r'[ ,]',s)).most_common(1)[0][0]))

22

Upvotes: 0

Richard Sprague
Richard Sprague

Reputation: 353

Here's a simpler version, more closely following your original style.

sentence= input("Enter a sentence")
keyword= input("Input a keyword from the sentence")
words = sentence.split(' ')

for i, word in enumerate(words):
    if keyword == word:
        print(i+1)  # if you want the index to start at 1, not 0

the Python enumerate function returns both the index of your word, as well as the word itself.

Upvotes: 0

Related Questions