Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python3
- # -*- coding: utf-8 -*-
- # Filename: word_count.py
- # Author: Jeoi Reqi
- """
- Word Count Script
- This script reads text from a specified file in the same directory and counts
- the occurrences of each word in the text. It utilizes a function, count_words,
- to perform the word counting operation.
- Requirements:
- - Python 3
- Usage:
- 1. Save the text file in the same directory as the script.
- 2. Replace 'texty.txt' with the actual file name in the script.
- 3. Run the script.
- 4. The script will display the occurrences of each word in the text.
- 5. The script will prompt the user if they want to save the ordered word count data to a file.
- Note: The output file sorts the words by the occurence values.
- """
- import string
- from collections import Counter
- def count_words(text):
- """Count the occurrences of each word in a given sentence.
- Args:
- text (str): Text.
- Returns:
- dict: Dictionary with the occurrences of each word.
- """
- # Remove punctuation and convert to lowercase
- cleaned_text = ''.join(char.lower() if char.isalnum() or char.isspace() else ' ' for char in text)
- # Split the text into words and count occurrences
- word_counts = Counter(cleaned_text.split())
- return dict(word_counts)
- def read_text_from_file(file_path):
- """Read text from a file.
- Args:
- file_path (str): Path to the file.
- Returns:
- str: Text read from the file.
- """
- with open(file_path, 'r', encoding='utf-8') as file:
- return file.read()
- def save_to_file(word_counts):
- """Save word count data to 'wordcount.txt' ordered by occurrence value.
- Args:
- word_counts (dict): Dictionary with word occurrences.
- """
- sorted_counts = sorted(word_counts.items(), key=lambda x: x[1], reverse=True)
- with open('wordcount.txt', 'w', encoding='utf-8') as file:
- current_count = None
- for word, count in sorted_counts:
- if count != current_count:
- if current_count is not None:
- file.write('\n')
- file.write(f"Occurence Count: {count}\n")
- file.write("---------------\n")
- current_count = count
- file.write(f"{word}\n")
- def main():
- # Specify the file path
- file_path = 'texty.txt' # Replace 'texty.txt' with the actual file name
- # Read text from the file
- text = read_text_from_file(file_path)
- # Count words
- word_counts = count_words(text)
- # Display the result
- print("\n\n\n\n::[ Occurrences of each word in the text ]::\n")
- for word, count in word_counts.items():
- print(f"\t\t{word}: {count}")
- # Ask the user if they want to save the word count data to a file
- print("\n\n\n::[ Options ]::\n")
- print("1. Save word count data to 'wordcount.txt'.")
- print("2. Do not save the word count data.")
- user_choice = input("\nEnter your choice (1 or 2): ")
- # Process user's choice
- if user_choice == '1':
- save_to_file(word_counts)
- print("Word count data saved to 'wordcount.txt'.")
- elif user_choice != '2':
- print("Invalid choice. Word count data not saved.")
- if __name__ == "__main__":
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement