Py99 Sam
Py99 Sam
A13. Write a Python Program to Count the Occurrences of a Word in a Text File.
Solution:
Python Code:
except FileNotFoundError:
print(f"Error: The file '{file_name}' was not found.")
# Example usage
file_name = 'sample.txt' # Replace with the path to your file
target_word = 'python' # Replace with the word you want to search
count_word_occurrences(file_name, target_word)
Algorithm:
2. Read the content of the file and convert it to lowercase (to handle case insensitivity).
5. Display the result showing how many times the word occurs.
Existing file:[Id-marks1-marks2-marks3-marks4-marks5]
110011 89 67 75 90 56
110101 78 88 50 92 72
110102 60 70 56 91 51
110201 77 88 60 71 67
110202 55 61 71 62 73
New file will contain the lines with average marks more than 65.
Solution:
Python Code:
except FileNotFoundError:
print(f"Error: The file '{input_file}' was not found.")
# Example usage
input_file = 'existing_file.txt' # Replace with your input file path
output_file = 'new_file.txt' # Replace with your output file path
filter_high_average(input_file, output_file)
Algorithm:
o If the average is greater than 65, store the line in the new file.