Untitled

 avatar
unknown
plain_text
5 months ago
3.2 kB
8
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")
print("Files in this directory: ", os.listdir())

# This puts the folder path and the file name together to make the full path
while True:
    file_path = input("Enter the file path (inside monty_python_sketches): ")
    file_path = "monty_python_sketches/" + file_path
    path = os.path.join(cwd, file_path)
    if os.path.exists(path):
        print("Full file path:", path)
        break
    print(f"File path '{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

# Open the file to read its contents
try:
    with open(file_path, "r") as file_connection:
        file_contents = file_connection.read()
except Exception as e:
    print(f"An error occurred while reading the file: {e}")

# Count the word or phrase, adjusting for case sensitivity
if case_sensitive == 'no':
    word_count = file_contents.lower().count(word.lower()) 
else:
    word_count = file_contents.count(word)

# Print the result
result_value = f"The word/phrase '{word}' was found {word_count} times in this file: {file_path}"
print(result_value)

# Write the result to a text file
with open("wordcount_results.txt", "w") as result:
    result.write(result_value)

# Add feature: Count occurrences of the word in all '.txt' files in the directory
files = os.listdir("monty_python_sketches")
files_name_list = []
word_count_list = []

for file_name in files:
    if file_name.endswith(".txt"):
        file_path = os.path.join(cwd, "monty_python_sketches", 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