From the class Code as a Liberal Art · Spring 2022
part1/unit2_hw1_a.py
file = open("u2t1-2022-sotu.txt","r")
word_counts = {}
for line in file:
for word in line.split():
if word in word_counts:
word_counts[word] = word_counts[word] + 1
else:
word_counts[word] = 1
print( "There were " + str( len(word_counts) ) +
" total words in this text.")
file.seek(0)
most_frequent_word = file.readline().split()[0]
for word in word_counts:
if word_counts[word] > word_counts[most_frequent_word]:
most_frequent_word = word
print("The most frequent word is: " + str(most_frequent_word) +
" and it occurs " +
str(word_counts[most_frequent_word]) + " times.")
part1/unit2_hw1_b.py
file = open("u2t1-2022-sotu.txt","r")
word_counts = {}
stop_words = {"the", "to", "and", "of", "a", "in", "we", "And", "is", "for", "I", "our", "that", "will", "with", "have", "on", "are", "We", "their", "from", "it", "more","can", "The", "at", "this", "as", "be", "so",}
for line in file:
for word in line.split():
if word in stop_words:
continue
if word in word_counts:
word_counts[word] = word_counts[word] + 1
else:
word_counts[word] = 1
print( "There were " + str( len(word_counts) ) +
" total words in this text.")
file.seek(0)
most_frequent_word = file.readline().split()[0]
for word in word_counts:
if word_counts[word] > word_counts[most_frequent_word]:
most_frequent_word = word
print("The most frequent non-stop-word word is: " + str(most_frequent_word) +
" and it occurs " +
str(word_counts[most_frequent_word]) + " times.")
part1/unit2_hw1_c.py
file = open("u2t1-2022-sotu.txt","r")
word_counts = {}
stop_words = {"the", "to", "and", "of", "a", "in", "we", "And", "is", "for", "I", "our", "that", "will", "with", "have", "on", "are", "We", "their", "from", "it", "more","can", "The", "at", "this", "as", "be", "so","you", "your", "not", "make", "has", "get", "they", "But", "was", "than", "who", "know", "my", "new", "up", "do", "by", "one", "if", "keep", "all", "us", "most", "an", "he", "every", "That’s","going", "never", "why", "other", "–", "pass", "America", "let’s", "Let’s", "He", "when", "It", "like", "Our", "I’m", "lower", "also", "his" }
for line in file:
for word in line.split():
if word in stop_words:
continue
if word in word_counts:
word_counts[word] = word_counts[word] + 1
else:
word_counts[word] = 1
print( "There were " + str( len(word_counts) ) +
" total words in this text.")
file.seek(0)
most_frequent_word = file.readline().split()[0]
for word in word_counts:
if word_counts[word] > word_counts[most_frequent_word]:
most_frequent_word = word
print("The most frequent non-stop-word word is: " + str(most_frequent_word) +
" and it occurs " +
str(word_counts[most_frequent_word]) + " times.")
sorted_words = sorted(word_counts, key=word_counts.get, reverse=True)
for i in range(10):
w = sorted_words[i]
print( w + " " + str(word_counts[ w ]))