1

I have a text file that I want to extract different words from, using a position index given by the user. for example, the text is: i believe i can fly i believe i can touch the sky i think about it every night and day spread my wings and fly away

I want a function to return a word, so if the user entered 7 iwll return believe.

sorry for formatting i'm new here. Thank you

dvd
  • 23
  • 1
  • 3

3 Answers3

0

Simply by splitting the text

text = "i believe i can fly i believe i can touch the sky i think about it every night and day spread my wings and fly away".split(" ")

and then

text[6] = "believe"

indexes always start from 0 so you have to take user input minus 1

def get_word(phrase, user_input):
  index = user_input - 1
  text = phrase.split(" ")

  return text[index] if index <= len(text) else "Can't find word at index {}".format(index)
MSR974
  • 632
  • 3
  • 12
0
a = "i believe i can fly i believe i can touch the sky i think about it every night and day spread my wings and fly away"

words = a.split()

def word_return(index):
    return words[index] if index < len(words) else "Index Not found"

index = int(input("enter index"))
print(word_return(index-1))
bigbounty
  • 16,526
  • 5
  • 37
  • 65
0

I assumed that you have 'txt' file in the same folder in which you stored your python file, if not then write the location of file instead of file name in the following code, else it will run successfully.

f=open("file_name.txt")
index=int(input("Enter the index number please : "))
seperate=list(f.read().split(" "))
print(seperate[index-1])
f.close()

Output:-

Enter the index number please : 7
believe

I hope this will solve your problem. Happy coding ;)