The entire speech is saved in the text file “policy.txt”. Your goal is to find the top…
- User
The entire speech is saved in the text file “policy.txt”. Your goal is to find the top 20 most frequent words in the file and store them in a dictionary called top20words. The keys should be the capitalized words and the values should be their corresponding frequencies. Save the result in a descending order based on the frequency and then the word (if frequencies are the same). For example, the following are the most frequent and the least frequent words. {'GOVERNMENT': 60, 'CHIEF': 13} Notes:
- Punctuation in words: “government’s” is considered the same as “government”.
- Singular and plural: “government” and “governments” are considered as two different words.
- Hyphen/underscore in words: “my-government” is considered as two different words; “my_government” is considered as two different words.
- Word variations: “you”, “your” and “yours” are considered as three different words; “govern”, “governing”, and “governed” are considered as three different words; “government” and “governmental” are considered as two different words.
- Numbers: ignore all numbers such as 2.8, 10, 2019.
- Stop words: they refer to the most common words in a language such as “the,” “from,” and “are” in English. These words appear to be of little value. The text file “stop_words.txt” includes a list of common English stop words. Your top20words should not include any stop words listed in the file.
- Assistant
Here is a possible solution to your problem:
import re # Read the stop words from the file with open("stop_words.txt", "r") as f: stop_words = set(f.read().splitlines()) # Read the policy text from the file with open("policy.txt", "r") as f: text = f.read() # Split the text into words using regular expressions words = re.findall(r'\b\w+\b', text) # Count the frequency of each word word_counts = {} for word in words: # Check if the word is a stop word or a number if word.lower() not in stop_words and not word.isnumeric(): # Capitalize the word capitalized_word = word.upper() # Increment the count for the word word_counts[capitalized_word] = word_counts.get(capitalized_word, 0) + 1 # Sort the word counts in descending order based on frequency and word top20words = dict(sorted(word_counts.items(), key=lambda x: (-x[1], x[0]))[:20]) # Print the top 20 words and their frequencies for word, frequency in top20words.items(): print(word, frequency)