Find the most common word in song and replace it
Solution
deffind_highest_occurring(name):
“”” This function returns the highest-occurring word
in file lyrics.txt. The function uses a dictionary to
store the count of each word. “””
count = dict()
f = open(name, ‘r’)
for line in f:
words = line.strip().split()
for word in words:
count[word] = count.get(word, 0) + 1
f.close()
# get the most common word (saved into target)
target = None
for word, cnt in count.items():
if target == None or count[target] <cnt:
target = word
return target
def replace(fname1, oldword, fname2, newword):
“”” replace the old word with the new word in the first file. “””
f1 = open(fname1, ‘r’)
f2 = open(fname2, ‘w’)
for line in f1:
words = line.strip().split()
# replace the old word with the new word
for i in range(len(words)):
if words[i] == oldword:
words[i] = newword
# merge the words back to a line and save into the new file
line = ‘ ‘.join(words)
f2.write(line + “\n”)
f1.close()
f2.close()
if __name__ == ‘__main__’:
old = find_highest_occurring(‘lyrics.txt’)
# ask the user to enter the word to replace
print (‘The most common word:’, old)
new = input (‘Which word do you want to replace the most common word with: ‘)
# replace and save the output to a file
replace(‘lyrics.txt’, old, ‘new_lyrics.txt’, new)
print (‘The file is saved as’, ‘new_lyrics.txt’, ‘…’);