Untitled
unknown
plain_text
5 months ago
3.1 kB
4
Indexable
import os import csv #This is for the search input is either a single word or two def two_phrase(): while True: search_phrase = input("Enter a single word or two-word phrase to count: ").strip() words = search_phrase.split() # Split input into words if len(words) <= 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.") # Function to get case sensitivity preference from the user def get_case_sensitivity_preference(): while True: case_sensitive = input("Do you want the count 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'.") # Function to count occurrences of a 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() # Modify file contents based on case sensitivity if case_sensitive == 'no': return file_contents.lower().count(word.lower()) else: return file_contents.count(word) except Exception as e: print(f"An error occurred while reading the file: {e}") return 0 # Function to search a word in all files within a directory def search_word_in_files(directory_path, word_or_phrase, case_sensitive): results = [] files = os.listdir(directory_path) # Get all files in the directory for file_name in files: # Only process text files if file_name.endswith(".txt"): file_path = os.path.join(directory_path, file_name) with open(file_path, 'r') as file: file_contents = file.read() if case_sensitive == 'no': word_or_phrase = word_or_phrase.lower() file_contents = file_contents.lower() count = file_contents.count(word_or_phrase) results.append((file_name, count)) print(f"Count of '{word_or_phrase}' in '{file_name}': {count}") return results #This is to implement results to CSV def write_results_to_csv(results, csv_file): try: with open(csv_file, mode='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}") #Here is where the execution starts directory_path = input("Enter the directory path: ") search_phrase = two_phrase() case_sensitive = get_case_sensitivity_preference() #This will word search and collect results results = search_word_in_files(directory_path, search_phrase, case_sensitive) #This will Write results to CSV csv_file = "wordcount_results.csv" write_results_to_csv(results, csv_file)
Editor is loading...
Leave a Comment