Answered step by step
Verified Expert Solution
Question
1 Approved Answer
Q:Write Python code that reads text from a provided file, searches for a specific word in the text, and returns the position ( line number
Q:Write Python code that reads text from a provided file, searches for a specific word in the text, and returns the position line number of the first occurrence of this word.
Instructions:
Open and read the contents of the file sample.txt given below as example
Iterate through each line of the text to find the first occurrence of the word. Remember to keep track of the line number.
Once the word is found, return the line number to the user.
If the word is not found after iterating through all lines, inform the user that the word does not exist in the text by returning "Does not exist".
Example:
Sample.txt
Hello and welcome to the Python exercise.
This text contains multiple lines and words for you to search. Try finding different words to see how effective your function is Remember the position should reflect the line number of the text that you want to search. Good luck with your Python coding journey.
If the word to be searched is "Python", the expected output should be "Line Write a function findword and make sure the output eg Line is returned using the function.
Hint: You may start with the code below to first read the text from the file as separate lines.
with opensampletxt as file:
text file.read
lines text.split
In this exercise, it's recommended to use the 'split function. The 'split' function is used to split a string into a list of substrings based on a specified delimiter. When you call split on a string, you provide the delimiter as an argument, and Python returns a list of substrings obtained by splitting the original string wherever the delimiter occurs.
For example:
text "apple banana orange"
fruits text.split # splits by space
fruits is a list with items apple "banana", "orange"
text "apole.banana.orange"
ANS: def findwordword:
with opensampletxt as file:
text file.read
lines text.split
# Split by newline character to preserve line breaks
linenumber # Start line numbering from
for line in lines:
if word in line:
return fLine linenumber
linenumber
return "Does not exist"
# Tests
printFind Word:"
printfindwordPython
printfindwordposition
printfindwordcomputer
Can you fix and tell why this code is not working. And make it workable code
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started