Untitled
unknown
plain_text
a year ago
2.4 kB
7
Indexable
# This is import for the path file
import os
import csv
# This is for the search input: either a single word or two-word phrase
def two_phrase():
while True:
search_two = input("Enter here a single or two-word phrase to count: ").strip()
if len(search_two.split()) > 2:
print("Error: You can only search for single words or two-word phrases.")
else:
return search_two
# This is to get the working directory
cwd = os.getcwd()
print(cwd, "Current working directory")
# This asks the user for the directory containing text files
while True:
dir_path = input("Enter the directory path (e.g., 'monty_python_sketches'): ")
dir_path = os.path.join(cwd, dir_path)
if os.path.isdir(dir_path):
print(f"Full directory path: {dir_path}")
break
print(f"Directory path '{dir_path}' is invalid. Please try again.")
# Ask the user for the word or phrase to count
word = two_phrase()
# Ask for case sensitivity
while True:
case_sensitive = input("Do you want the count to be case sensitive? (yes/no): ").strip().lower()
if case_sensitive in ['yes', 'no']:
break
# List all text files in the directory and count occurrences of the word/phrase
files_name_list = []
word_count_list = []
for file_name in os.listdir(dir_path):
if file_name.endswith(".txt"):
file_path = os.path.join(dir_path, file_name)
try:
with open(file_path, "r") as file:
file_contents = file.read()
if case_sensitive == 'no':
word = word.lower()
file_contents = file_contents.lower()
count = file_contents.count(word)
files_name_list.append(file_name)
word_count_list.append(count)
print(f"Count of '{word}' in '{file_name}': {count}")
except Exception as e:
print(f"An error occurred while processing '{file_name}': {e}")
# Write the search results for all files to a CSV file
csv_file = "wordcount_results.csv"
try:
with open(csv_file, mode='a', newline='') as file:
writer = csv.writer(file)
for x in range(len(files_name_list)):
writer.writerow([files_name_list[x], word_count_list[x]])
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}")
Editor is loading...
Leave a Comment