To solve this problem, we need to create a Python script that searches for a specific string in a given file, reports the line numbers where the string appears, counts occurrences per line, and provides a total count of occurrences. The script should handle common errors (like file not found or permission issues) and offer an option for case-sensitive or case-insensitive search.
Approach
-
Input Handling:
- Prompt the user for the file path.
- Prompt for the search string (ensure it's not empty).
- Ask if the search should be case-sensitive.
-
File Processing:
- Open the file in read mode (with error handling for common issues like missing files or permission errors).
- Read the file line by line to avoid memory issues with large files.
- For each line, check if the search string exists (considering case sensitivity).
- Count occurrences per line and total occurrences.
-
Output:
- Print lines where the string is found (with line numbers and occurrence count per line).
- Print the total number of occurrences or a message if no matches are found.
Solution Code
def search_file():
# Get file path from user
file_path = input("Enter the path to the file you want to search: ").strip()
# Get non-empty search string
while True:
search_str = input("Enter the string to search for: ").strip()
if search_str:
break
print("Error: Search string cannot be empty. Please try again.")
# Case sensitivity option
case_sensitive = input("Perform case-sensitive search? (y/n): ").strip().lower() == 'y'
try:
with open(file_path, 'r', encoding='utf-8') as file:
line_number = 0
total_occurrences = 0
for line in file:
line_number += 1
# Adjust for case sensitivity
if case_sensitive:
line_check = line
str_check = search_str
else:
line_check = line.lower()
str_check = search_str.lower()
# Check for matches
if str_check in line_check:
count_in_line = line_check.count(str_check)
total_occurrences += count_in_line
# Print the original line (without trailing newline)
print(f"\nLine {line_number}: {line.rstrip()}")
print(f"Occurrences in this line: {count_in_line}")
# Final report
if total_occurrences == 0:
print(f"\nNo occurrences of '{search_str}' found in the file.")
else:
print(f"\nTotal occurrences of '{search_str}': {total_occurrences}")
except FileNotFoundError:
print(f"\nError: File '{file_path}' not found.")
except PermissionError:
print(f"\nError: You do not have permission to read '{file_path}'.")
except UnicodeDecodeError:
print(f"\nError: The file '{file_path}' is not a text file (binary or unsupported encoding).")
except Exception as e:
print(f"\nUnexpected error: {str(e)}")
if __name__ == "__main__":
search_file()
Explanation
- Input Validation: The script ensures the search string is not empty to avoid invalid searches.
- Case Sensitivity: Users can choose between case-sensitive and case-insensitive searches, making the tool flexible.
- Error Handling: The script catches common errors (file not found, permission issues, non-text files) and provides meaningful messages to the user.
- Efficiency: Reading the file line by line ensures that even large files are processed without excessive memory usage.
- Clear Output: The script prints the exact lines where the string is found, along with line numbers and occurrence counts, making it easy to locate matches.
This script is user-friendly and robust, suitable for both basic and slightly advanced search needs in text files.

作者声明:本文包含人工智能生成内容。