Reputation: 1
I need to develop a program on python that identifies individual words in a sentence and stores them in a list but stores a word's position number in the sentence not the actual word. I have developed this code yet cannot get it to save the words position.
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)
file = open("newfile.txt","a")
file.write(input("text to write in the file")+"/n")
file.close()
Anyone got any advice, pointers or help?
Upvotes: 0
Views: 120
Reputation: 4000
Based on you question and the code snippet, I have come to a conclusion that your program,
So, for that, Here's the code.
sentence= input("Enter a sentence")
keyword= input("Input a keyword from the sentence")
words = sentence.split(' ')
file=open("newfile.txt","a") #open the file in append mode
for i, word in enumerate(words):
if keyword == word:
file.write(str(i+1)+" ") #append the text. I've added space to distiguish digit.
file.close() #Close the file after loop.
Upvotes: 1