Untitled
unknown
plain_text
5 months ago
2.8 kB
5
Indexable
import os import csv # This is for the search input, either a single word or two-word phrase def two_phrase(): while True: search_phrase = input("Enter a single word or two-word phrase to count: ").strip() if len(search_phrase.split()) <= 2: # Check if it's one or two words return search_phrase else: print("Error: You can only search for a single word or two-word phrase.") # Ask case sensitivity def get_case_sensitivity(): while True: case_sensitive = input("Do you want the search to be case sensitive? (yes/no): ").strip().lower() if case_sensitive in ['yes', 'no']: return case_sensitive else: print("Invalid input. Please enter 'yes' or 'no'.") # Count word or phrase in a single file def count_word_in_file(file_path, word, case_sensitive): try: with open(file_path, "r") as file_connection: file_contents = file_connection.read() if case_sensitive == 'no': # If not case sensitive, make everything lowercase return file_contents.lower().count(word.lower()) else: return file_contents.count(word) except FileNotFoundError: print(f"Error: File '{file_path}' not found.") return 0 except Exception as e: print(f"An unexpected error occurred: {e}") return 0 # Count word or phrase in all files within a directory def count_word_in_directory(directory_path, word, case_sensitive): results = [] for file_name in os.listdir(directory_path): # Get all files in the directory file_path = os.path.join(directory_path, file_name) if os.path.isfile(file_path) and file_name.endswith(".txt"): # Only text files word_count = count_word_in_file(file_path, word, case_sensitive) results.append((file_name, word_count)) # Store file name and count print(f"Count of '{word}' in '{file_name}': {word_count}") return results # Write results to CSV file def write_results_to_csv(results, csv_file): try: with open(csv_file, "a", newline='') as file: writer = csv.writer(file) for result in results: writer.writerow(result) print(f"Results have been written to '{csv_file}'.") except Exception as e: print(f"An error occurred while writing to the CSV file: {e}") # Main program starts here directory_path = input("Enter the directory path: ") search_phrase = two_phrase() case_sensitive = get_case_sensitivity() # Search word or phrase in files and get results results = count_word_in_directory(directory_path, search_phrase, case_sensitive) # Write results to CSV file csv_file = "wordcount_results.csv" write_results_to_csv(results, csv_file)
Editor is loading...
Leave a Comment