-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathanalyze_lyrics.py
More file actions
266 lines (237 loc) · 7.94 KB
/
analyze_lyrics.py
File metadata and controls
266 lines (237 loc) · 7.94 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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
# -*- coding: utf-8 -*-
import csv
import json
LYRICS_FILE = "data/lyrics.json"
WORDS_FILE = "data/words.csv"
OUTPUT_FILE = "data/analysis.json"
SONG_OUTPUT_FILE = "data/song_analysis.csv"
possessiveWords = {
'his': 'male',
'her': 'female',
'my': 'self',
'ma': 'self',
'your': 'opposite',
'you': 'opposite',
'ya': 'opposite'
}
subjectWords = {
'he': 'male',
'she': 'female',
'i': 'self',
'you': 'opposite'
}
objectWords = {
'him': 'male',
'her': 'female',
'me': 'self',
'you': 'opposite'
}
wordBuffer = 4
regionMatchCount = 3
songMatchCount = 20
songs = []
words = []
data = []
song_data = []
# Read words
with open(WORDS_FILE, 'rb') as f:
r = csv.DictReader(f)
for row in r:
words.append(row)
# Read songs/lyrics
with open(LYRICS_FILE) as f:
songs = json.load(f)
def is_number(s):
try:
float(s)
return True
except ValueError:
return False
# Add data
def addData(song, region, value):
global data
artist = song['artist']
matches = [d for d in data if artist==d['artist']]
match = matches[0]
i = match['index']
# Look for gendered matches
regionFound = False
for j,r in enumerate(match['regions']):
if r['name']==region:
regionFound = True
data[i]['regions'][j]['value'] += value
break
if not regionFound:
data[i]['regions'].append({
'name': region,
'value': value
})
data[i]['value_count'] += value
# Look for gender-agnostic matches
regionFound = False
region = region.split('_')[-1]
for j,r in enumerate(match['regions_agnostic']):
if r['name']==region:
regionFound = True
data[i]['regions_agnostic'][j]['value'] += value
break
if not regionFound:
data[i]['regions_agnostic'].append({
'name': region,
'value': value
})
def addSongData(song, region):
global song_data
matches = [d for d in song_data if song['artist']==d['artist'] and song['song']==d['song'] and song['album']==d['album']]
match = matches[0]
i = match['index']
regionFound = False
for j,r in enumerate(match['regions']):
if r['name']==region:
regionFound = True
song_data[i]['regions'][j]['value'] += 1
break
if not regionFound:
song_data[i]['regions'].append({
'name': region,
'value': 1
})
# Add word count
def addWordCount(artist, value):
global data
matches = [d for d in data if artist==d['artist']]
match = matches[0]
data[match['index']]['word_count'] += value
def swapGender(gender):
if gender=='male':
return 'female'
else:
return 'male'
# Init data
for s in songs:
if not [d for d in data if d['artist']==s['artist']]:
data.append({
'index': len(data),
'artist': s['artist'],
'regions': [],
'regions_agnostic': [],
'word_count': 0,
'value_count': 0
})
song_data.append({
'index': len(song_data),
'artist': s['artist'],
'song': s['song'],
'album': s['album'],
'url': s['url'],
'regions': [],
'score': 0
})
print "Analyzing..."
# Analyze each song
for song in songs:
lWords = song['lyrics'].split(' ')
for i,lw in enumerate(lWords):
bufferLeft = lWords[max(i-wordBuffer,0):i]
bufferRight = lWords[min(i+1,len(lWords)-1):min(i+1+wordBuffer,len(lWords)-1)]
matches = [w for w in words if w['word']==lw]
for match in matches:
# This word could apply to either gender
if match['gender']=='both':
gender = ""
# Look left for gendered possessive words (e.g. his face)
for w in bufferLeft:
if w in possessiveWords:
gender = possessiveWords[w]
break
# Determine gender for self/opposite
if gender=='self':
gender = song['gender']
elif gender=='opposite':
gender = swapGender(song['gender'])
# Found gender, add that gender
if gender:
addData(song, gender+'_'+match['region'], 2)
addSongData(song, match['region'])
# Add both genders
else:
addData(song, 'male_'+match['region'], 1)
addData(song, 'female_'+match['region'], 1)
addSongData(song, match['region'])
# gender-specific body part, add value of two
else:
addData(song, match['gender']+'_'+match['region'], 2)
addSongData(song, match['region'])
addWordCount(song['artist'], len(lWords))
print "Finished analysis. Calculating percentages..."
# Determine percents
minValue = None
maxValue = None
minValueAgnostic = None
maxValueAgnostic = None
for i, d in enumerate(data):
for j, r in enumerate(d['regions']):
# Normalize values to percent of value count
value_n = 1.0 * r['value'] / d['value_count']
data[i]['regions'][j]['value_n'] = value_n
# Track min/max
if minValue is None or value_n < minValue:
minValue = value_n
if maxValue is None or value_n > maxValue:
maxValue = value_n
for j, r in enumerate(d['regions_agnostic']):
# Normalize values to percent of value count
value_n = 1.0 * r['value'] / d['value_count']
data[i]['regions_agnostic'][j]['value_n'] = value_n
# Track min/max
if minValueAgnostic is None or value_n < minValueAgnostic:
minValueAgnostic = value_n
if maxValueAgnostic is None or value_n > maxValueAgnostic:
maxValueAgnostic = value_n
print "Finished percentages. Normalizing and sorting..."
# Normalize to 0-1
for i, d in enumerate(data):
for j, r in enumerate(d['regions']):
data[i]['regions'][j]['value_n'] = (r['value_n']-minValue) / (maxValue-minValue)
for j, r in enumerate(d['regions_agnostic']):
data[i]['regions_agnostic'][j]['value_n'] = (r['value_n']-minValueAgnostic) / (maxValueAgnostic-minValueAgnostic)
# Sort regions
data[i]['regions'] = sorted(data[i]['regions'], key=lambda k: k['value_n'], reverse=True)
data[i]['regions_agnostic'] = sorted(data[i]['regions_agnostic'], key=lambda k: k['value_n'], reverse=True)
print "Finished normalizing and sorting. Calculating top song matches..."
for i, d in enumerate(data):
# Get the artist's top mentioned regions
top_regions = []
for j, r in enumerate(d['regions_agnostic']):
if j < regionMatchCount:
top_regions.append(r['name'])
# Retrieve artist's songs
artist_songs = [s for s in song_data if s['artist']==d['artist']]
# Give each song a score based on top mentioned regions
for j, s in enumerate(artist_songs):
for r in s['regions']:
if r['name'] in top_regions:
artist_songs[j]['score'] += r['value']
# Sort songs by score
artist_songs = sorted(artist_songs, key=lambda k: k['score'], reverse=True)
# Add songs to data
data[i]['top_songs'] = artist_songs[:songMatchCount]
# Save data
with open(OUTPUT_FILE, 'w') as f:
json.dump(data, f)
print('Successfully wrote ' + str(len(data)) + ' artists to JSON file: '+OUTPUT_FILE)
# Save song data
with open(SONG_OUTPUT_FILE, 'wb') as f:
w = csv.writer(f)
headers = ['artist', 'song', 'album', 'url', 'score']
w.writerow(headers)
for d in data:
for s in d['top_songs']:
row = []
for h in headers:
if isinstance(s[h], basestring):
row.append(s[h].encode('utf-8'))
else:
row.append(s[h])
w.writerow(row)
print('Successfully wrote to song data file: '+SONG_OUTPUT_FILE)