Advertisement
Python253

word_count

Mar 3rd, 2024 (edited)
724
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.25 KB | None | 0 0
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. # Filename: word_count.py
  4. # Author: Jeoi Reqi
  5.  
  6. """
  7. Word Count Script
  8.  
  9. This script reads text from a specified file in the same directory and counts
  10. the occurrences of each word in the text. It utilizes a function, count_words,
  11. to perform the word counting operation.
  12.  
  13. Requirements:
  14. - Python 3
  15.  
  16. Usage:
  17. 1. Save the text file in the same directory as the script.
  18. 2. Replace 'texty.txt' with the actual file name in the script.
  19. 3. Run the script.
  20. 4. The script will display the occurrences of each word in the text.
  21. 5. The script will prompt the user if they want to save the ordered word count data to a file.
  22.  
  23. Note: The output file sorts the words by the occurence values.
  24. """
  25.  
  26. import string
  27. from collections import Counter
  28.  
  29. def count_words(text):
  30.     """Count the occurrences of each word in a given sentence.
  31.  
  32.    Args:
  33.        text (str): Text.
  34.  
  35.    Returns:
  36.        dict: Dictionary with the occurrences of each word.
  37.  
  38.    """
  39.     # Remove punctuation and convert to lowercase
  40.     cleaned_text = ''.join(char.lower() if char.isalnum() or char.isspace() else ' ' for char in text)
  41.    
  42.     # Split the text into words and count occurrences
  43.     word_counts = Counter(cleaned_text.split())
  44.    
  45.     return dict(word_counts)
  46.  
  47. def read_text_from_file(file_path):
  48.     """Read text from a file.
  49.  
  50.    Args:
  51.        file_path (str): Path to the file.
  52.  
  53.    Returns:
  54.        str: Text read from the file.
  55.  
  56.    """
  57.     with open(file_path, 'r', encoding='utf-8') as file:
  58.         return file.read()
  59.  
  60. def save_to_file(word_counts):
  61.     """Save word count data to 'wordcount.txt' ordered by occurrence value.
  62.  
  63.    Args:
  64.        word_counts (dict): Dictionary with word occurrences.
  65.  
  66.    """
  67.     sorted_counts = sorted(word_counts.items(), key=lambda x: x[1], reverse=True)
  68.  
  69.     with open('wordcount.txt', 'w', encoding='utf-8') as file:
  70.         current_count = None
  71.         for word, count in sorted_counts:
  72.             if count != current_count:
  73.                 if current_count is not None:
  74.                     file.write('\n')
  75.                 file.write(f"Occurence Count: {count}\n")
  76.                 file.write("---------------\n")
  77.                 current_count = count
  78.             file.write(f"{word}\n")
  79.  
  80. def main():
  81.     # Specify the file path
  82.     file_path = 'texty.txt'  # Replace 'texty.txt' with the actual file name
  83.  
  84.     # Read text from the file
  85.     text = read_text_from_file(file_path)
  86.  
  87.     # Count words
  88.     word_counts = count_words(text)
  89.  
  90.     # Display the result
  91.     print("\n\n\n\n::[ Occurrences of each word in the text ]::\n")
  92.     for word, count in word_counts.items():
  93.         print(f"\t\t{word}: {count}")
  94.  
  95.     # Ask the user if they want to save the word count data to a file
  96.     print("\n\n\n::[ Options ]::\n")
  97.     print("1. Save word count data to 'wordcount.txt'.")
  98.     print("2. Do not save the word count data.")
  99.     user_choice = input("\nEnter your choice (1 or 2): ")
  100.  
  101.     # Process user's choice
  102.     if user_choice == '1':
  103.         save_to_file(word_counts)
  104.         print("Word count data saved to 'wordcount.txt'.")
  105.     elif user_choice != '2':
  106.         print("Invalid choice. Word count data not saved.")
  107.  
  108. if __name__ == "__main__":
  109.     main()
  110.  
  111.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement