def count_words(text):
words = text.split()
return len(words)
def main():
print("Word Counter")
# Choose between input from the user or reading from a file
source = input("Enter '1' to input text, '2' to read from a file: ")
if source == '1':
# Input text from the user
user_input = input("Enter the text: ")
word_count = count_words(user_input)
print(f"Word count: {word_count}")
elif source == '2':
# Read text from a file
file_path = input("Enter the file path: ")
try:
with open(file_path, 'r') as file:
file_text = file.read()
word_count = count_words(file_text)
print(f"Word count: {word_count}")
except FileNotFoundError:
print("File not found. Please check the file path.")
else:
print("Invalid choice. Please enter '1' or '2'.")
if __name__ == "__main__":
main()from collections import Counter
import string
def count_words(text):
# Remove punctuation and convert to lowercase
cleaned_text = text.translate(str.maketrans("", "", string.punctuation)).lower()
# Split the text into words
words = cleaned_text.split()
# Count the frequency of each word
word_count = Counter(words)
return word_count
def main():
print("Word Counter")
# Choose between input from the user or reading from a file
source = input("Enter '1' to input text, '2' to read from a file: ")
if source == '1':
# Input text from the user
user_input = input("Enter the text: ")
word_count = count_words(user_input)
# Display word count
print(f"\nWord count: {sum(word_count.values())}\n")
# Display word frequency
print("Word frequency:")
for word, frequency in word_count.items():
print(f"{word}: {frequency}")
elif source == '2':
# Read text from a file
file_path = input("Enter the file path: ")
try:
with open(file_path, 'r') as file:
file_text = file.read()
word_count = count_words(file_text)
# Display word count
print(f"\nWord count: {sum(word_count.values())}\n")
# Display word frequency
print("Word frequency:")
for word, frequency in word_count.items():
print(f"{word}: {frequency}")
except FileNotFoundError:
print("File not found. Please check the file path.")
else:
print("Invalid choice. Please enter '1' or '2'.")
if __name__ == "__main__":
main()
Comments
Post a Comment