-
Notifications
You must be signed in to change notification settings - Fork 0
/
frequency.py
44 lines (34 loc) · 976 Bytes
/
frequency.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
import sys
import json
reload(sys)
sys.setdefaultencoding('utf8')
frequencies = {}
def getTweets(fp):
tweets = []
for line in fp:
data = json.loads(line)
# Only parse tweets with text
if "text" in data:
tweets.append(data['text'])
return tweets
def parseTweetsAndReturnTotalNumberOfTerms(tweets):
totalNumberOfTerms = 0
for tweet in tweets:
for word in tweet.split():
totalNumberOfTerms += 1
if word in frequencies:
frequencies[word] += 1
else:
frequencies[word] = 1
return totalNumberOfTerms
def main():
global totalNumberOfTerms
tweet_file = open(sys.argv[1])
tweets = getTweets(tweet_file)
totalNumberOfTerms = parseTweetsAndReturnTotalNumberOfTerms(tweets)
# Print frequency
for i, (term, frequency) in enumerate(frequencies.items()):
result = float(frequency)/float(totalNumberOfTerms)
print(term + ' ' + str(result))
if __name__ == '__main__':
main()