-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathanalyze_song_lyrics.py
More file actions
68 lines (60 loc) · 2.04 KB
/
analyze_song_lyrics.py
File metadata and controls
68 lines (60 loc) · 2.04 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# Analyze song lyrics - example for use python dictionaries
'''
In this example you can see how to create a frequency dictionary mapping str:int.
Find a word that occures the most and how many times.
Find the words that occur at least X times.
'''
def lyrics_frequencies(lyrics):
'''
Creates a Dictionary with the lyrics words and the frequency of each word.
Arguments:
lyrics - text.
'''
myDict = {}
for word in str(lyrics).split():
if word in myDict:
myDict[word] +=1
else:
myDict[word] = 1
return myDict
# Find the most common word - return a tuple (word, frequency).
# In case that there is more than one word returns a list.
def most_common_word(freqs):
'''
Find the most common word - return a tuple (word, frequency).
In case that there is more than one word returns a list.
Arguments:
freqs - a dictionary with words and frequncy of each word in the text.
'''
values = freqs.values()
best = max(values)
words = []
for k in freqs:
if freqs[k] == best:
words.append(k)
return (words, best)
def words_often(freqs, minTimes):
'''
Find the words that occur at least X times.
Each itereation deletes the most frequent words as long as the most frequent words
frequency is greater than the minTimes of occurences that the user gives.
Arguments:
freqs - a dictionary with words and frequncy of each word in the text.
minTimes - {int} - set by the user. The minimum number of occurences for each word.
'''
result = []
done = False
while done == False:
temp = most_common_word(freqs)
if temp[1] >= minTimes:
result.append(temp)
for w in temp[0]:
del(freqs[w])
else:
done = True
return result
if __name__ == "__main__":
with open(r'Muse_Invincible.txt', 'r') as f:
Invincible = f.read()
Invincible = lyrics_frequencies(Invincible)
print(words_often(Invincible, 4))