Question: 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:
1. read the contents of the file sample.txt ( written below as example)
2. Iterate through each line of the text to find the first occurrence of the word. Remember to keep track of the line number.
3. Once the word is found, return the line number to the user.
4. 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 1". Write a function find_word() and make sure the output "e.g. Line 1" 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 open("sample.txt") 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 3 items ["apple", "banana", "orange"]
text ="apole.banana.orange"
Answer:
Code 1( below): (Didn't work)
def find_word(filename, word):
"""
This function reads a text file, searches for a specific word, and returns the line number of the first occurrence.
Args:
filename (str): The name of the text file to read.
word (str): The word to search for.
Returns:
str: The line number of the first occurrence of the word (e.g., "Line 1") or "Does not exist" if not found.
"""
# Open the file in read mode
with open(filename,'r') as file:
# Initialize line counter
line_number =1
for line in file:
# Remove leading/trailing whitespace from the line (optional for better handling)
line = line.strip()
# Search for the word in the current line (case-insensitive)
if word.lower() in line.lower():
return f"Line {line_number}" # Return the line number with formatting
# Increment line counter for the next iteration
line_number +=1
# If the loop completes without finding the word, return "Does not exist"
return "Does not exist"
# Example usage with sample.txt (replace with your actual filename)
word_to_find = "Python" # Change this to the word you want to search
result = find_word("sample.txt", word_to_find)
print(result)
Code 2 below: ( didn't Work)
def find_word(word): with open("sample.txt") as file:
text file.read()
lines text.split("
")
line_number-1
if word in lines:
return f"Line {Line_number}"
line_number+-1
return "Does not exist"
# Tests
print("
Find Word")
print(find_word("Python")) print(find_word("position"))
print(find_word("computer"))
Code 3: (below): ( Worked)
def find_word(word):
with open("sample.txt") as file:
text = file.readlines()
line_number =1 # Start line numbering from 1
for line in text:
if word in line:
return f"Line {line_number}"
line_number +=1
return "Does not exist" # Word not found in any line
# Tests
print("Find Word:")
print(find_word("Python"))
print(find_word("position"))
print(find_word("computer"))
Explain In detail why Code 1 and code 2 were wrong and didn't work as compared to code 3 that worked and identify the mistake done in code 1 and code 2 and mistakes corrected in code 3 that worked

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!