I did this code:
sentence = input("Type in your sentance ").lower().split()
Word = input("What word would you like to find? ")
Keyword = Word.lower().split().append(Word)
positions = []
for (S, subword) in enumerate(sentence):
if (subword == Word):
positions.append
print("The word" , Word , "is in position" , S+1)
But there are 2 problems with it; I dont know how to write a code when the users word is not found and to but the positions in "The word position is in [1,3,6,9]. Any help? Thanks
Your code is having multiple errors. I am pasting here the sample code for your reference:
from collections import defaultdict
sentence_string = raw_input('Enter Sentence: ')
# Enter Sentence: Here is the content I need to check for index of all words as Yes Hello Yes Yes Hello Yes
word_string = raw_input("Enter Words: ")
# Enter Words: yes hello
word_list = sentence_string.lower().split()
words = word_string.lower().split()
my_dict = defaultdict(list)
for i, word in enumerate(word_list):
my_dict[word].append(i)
for word in words:
print "The word" , word, "is in position " , my_dict[word]
# The word yes is in position [21, 23, 24, 26]
# The word hello is in position [22, 25]
The approach here is:
sentence_string
here into list of wordsmy_dict
to store all the indexes of the words in word_list
words
to get your result with index, based on the value you store in my_dict
.Note: The commented part in above example is basically the output of the code.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments