/
get-data.py
176 lines (141 loc) · 5.37 KB
/
get-data.py
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
# -*- coding: utf-8 -*-
import feedparser, math
from BeautifulSoup import BeautifulSoup
from nltk import word_tokenize
from nltk.stem.porter import PorterStemmer
import nltk.data
from itertools import groupby
import json, time, collections, sys
from mixpanel import Mixpanel
from secrets import MIXPANEL
from datetime import datetime
import functools
import cPickle
def memoize(fctn):
memory = {}
@functools.wraps(fctn)
def memo(*args,**kwargs):
haxh = cPickle.dumps((args, sorted(kwargs.iteritems())))
if haxh not in memory:
memory[haxh] = fctn(*args,**kwargs)
return memory[haxh]
if memo.__doc__:
memo.__doc__ = "\n".join([memo.__doc__,"This function is memoized."])
return memo
from hyphen import Hyphenator
@memoize
def syllables(word):
try:
syllables = Hyphenator('hyph_en_GB.dic',
directory=u'/usr/share/hyphen/').syllables(unicode(word))
except ValueError:
syllables = []
return syllables if len(syllables) > 0 else [unicode(word)]
@memoize
def words(entry):
if type(entry) == unicode:
words = entry.split()
else:
words = entry.content[0].value.split()
return filter(lambda w: len(w) > 0,
[w.strip("0123456789!:,.?(){}[]") for w in words])
# return word_tokenize(entry.content[0].value)
# return entry.content[0].value.split(" ")
@memoize
def sentences(entry):
sent_detector = nltk.data.load('tokenizers/punkt/english.pickle')
return sent_detector.tokenize(entry.content[0].value)
def cleanup(data):
def cleaned(entry):
entry.counts = {'h2': entry.content[0].value.count("<h2>"),
'p': entry.content[0].value.count("\n\n")-entry.content[0].value.count("</h2>\n\n")}
entry.content[0].value = ''.join(BeautifulSoup(entry.content[0].value).findAll(text=True))
return entry
data.entries = map(cleaned, data.entries)
return data
def word_length(entry):
@memoize
def average():
return sum([len(syllables(w)) for w in words(entry)])\
/len(words(entry))
def deviation():
return math.sqrt(sum([(len(syllables(w))-average())**2 for w in words(entry)])\
/float(len(words(entry))))
return (average(), deviation())
def sentence_length(entry):
@memoize
def average():
return sum([len(words(s)) for s in sentences(entry)])\
/len(sentences(entry))
def deviation():
return math.sqrt(sum([(len(words(s))-average())**2 for s in sentences(entry)])\
/float(len(sentences(entry))))
return (average(), deviation())
def yule(entry):
# yule's I measure (the inverse of yule's K measure)
# higher number is higher diversity - richer vocabulary
stemmer = PorterStemmer()
d = collections.Counter([stemmer.stem(w).lower() for w in words(entry)])
M1 = float(len(d))
M2 = sum([len(list(g))*(freq**2) for freq,g in groupby(sorted(d.values()))])
try:
return (M1*M1)/(M2-M1)
except ZeroDivisionError:
return 0
def flesch_kincaid(entry):
#http://en.wikipedia.org/wiki/Flesch%E2%80%93Kincaid_readability_test
def syllable_count():
return sum([len(syllables(w)) for w in words(entry)])
return 206.835-1.015*(
len(words(entry))/float(len(sentences(entry)))
)-84.6*(
syllable_count()/float(len(words(entry)))
)
"""if __name__ == "__main__":
data = feedparser.parse('ageekwithahat.wordpress.2011-09-28.xml')
data = cleanup(data)
out = open('./blog-analysis.js', 'w')
out.write("analysis_data = [");
def line(entry):
if len(words(entry)) == 0:
return None
o = json.dumps({'flesch_kincaid': flesch_kincaid(entry),
'yule': yule(entry),
'word_len': word_length(entry),
'sentence_len': sentence_length(entry),
'date': time.strftime('%Y-%m-%d', entry.updated_parsed),
'words': len(words(entry)),
'sentences': len(sentences(entry))})
out.write(o+",\n")
print o
map(line, data.entries)
out.write("];");
out.close()
"""
if __name__ == "__main__":
data = feedparser.parse(sys.argv[1])
data = cleanup(data)
mx = Mixpanel(MIXPANEL['api_key'], MIXPANEL['api_secret'])
for entry in data.entries:
# print entry.wp_post_date_gmt.split(' ')[0]
# print entry.link
try:
date = datetime.strptime(entry.wp_post_date_gmt,
'%Y-%m-%d %H:%M:%S')
except ValueError:
continue
funnel = mx.request(['funnels'],
{'funnel_id': 6517,
'from_date': date.strftime('%Y-%m-%d'),
'where': 'url=='+entry.link})
if 'error' in funnel.keys():
print funnel
merged = {'completion': 0, 'starting_amount': 0, u'steps': 0, u'worst': 0}
for k in funnel['data'].keys():
for kk in funnel['data'][k]['analysis'].keys():
merged[kk] += funnel['data'][k]['analysis'][kk]
merged['steps'] = merged['steps']/len(funnel['data'])
print merged
# print mx.request(['funnels'],
# {'funnel_id': 6517,
# })