-
Notifications
You must be signed in to change notification settings - Fork 89
/
data2spreadsheet.py
152 lines (125 loc) · 3.67 KB
/
data2spreadsheet.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
try:
import json
except ImportError:
import simplejson as json
import codecs
import time
import datetime
import os
import random
import time
import sys
#Just used to highlight matches in tweets. This file does not query anything from Twitter!
queries=["term1","term2"]
outputDir = "output/" #Output directory
os.system("mkdir -p %s"%(outputDir)) #Create directory if doesn't exist
fhLog = codecs.open("LOG.txt",'a','UTF-8')
def logPrint(s):
fhLog.write("%s\n"%s)
print(s)
class Tweet:
def __init__(self):# word, url, hits, trackback, score, author, text):
self.keywords=[]
self.links=["","",""]
self.lang=""
self.langConf=""
@staticmethod
def csvHeader():
row = "\"\t\"".join(("URL", "Keywords", "Keyword Count", "DateTime", "Favorite Count", "Retweet", "Lang", "LinkCount", "Link1", "Link2", "Link3", "Author", "Text","Followers","Friends","Location","Timezone","UTC Offset"))
row = "\"%s\"\n"%row
return row
def csvRow(self):
row = "\"\t\"".join((
str(self.url),
",".join(self.keywords),
str(len(self.keywords)),
#str(datetime.datetime.fromtimestamp(self.date).strftime('%Y-%m-%d %H:%M:%S')),
str(self.date),
str(self.favorite),
str(self.retweet),
str(self.lang),
str(self.urlCount),
self.links[0],
self.links[1],
self.links[2],
self.author,
self.clean_text(),
str(self.followers),
str(self.friends),
self.location,
self.timezone,
str(self.utc)
))
row = "\"%s\"\n"%row
return row
def clean_text(self):
t = self.text.replace("\"","")
t = self.text.replace("\n"," ")
return t
def parse(self,json):
self.url="http://twitter.com/{0}/status/{1}".format(json["user"]["id_str"],json["id_str"])
self.date=json["created_at"]
self.favorite=json["favorite_count"]
self.retweet=json["retweet_count"]
self.author=json["user"]["screen_name"]
#"%s - Twitter"%json["trackback_author_name"] #This is retweet author's name
self.text=json["text"]
self.lang=json["lang"]
self.followers=json["user"]["followers_count"]
self.friends=json["user"]["friends_count"]
self.location=json["user"]["location"] if json["user"]["location"] else ""
self.timezone=json["user"]["time_zone"] if json["user"]["time_zone"] else ""
self.utc=json["user"]["utc_offset"] if json["user"]["utc_offset"] else ""
#Links
text = self.text
self.urlCount = text.count("http://") + text.count("https://")
count=0
words=text.split()
for w in words:
if w.count("http://") or w.count("https://"):
w=w[(w.find("http")):]
w=w.strip("():!?. \t\n\r")
if count>2:
self.links[2]=self.links[2]+","+w
else:
self.links[count]=w
count=count+1
def __hash__(self):
return hash(self.url, self.location)
def __eq__(self, other):
return (self.url)==(self.url)
allTweets={}
def parse(tweet):
tw=Tweet()
tw.parse(tweet)
if not (tw.url in allTweets):
txt=tw.text.lower()
for query in queries:
if query in txt:
tw.keywords.append(query)
#if len(tw.keywords)>0:
allTweets[tw.url]=tw
fhOverall=None
for file in sys.argv[1:]:
print(file)
fhb = codecs.open(file,"r")
firstLine=fhb.readline()
j=json.loads(firstLine)
if "statuses" in j:
#We have search API. The first (and only line) is a json object
for tweet in j["statuses"]:
parse(tweet)
else:
parse(j)
for line in fhb:
#We have search API, each line is a json object
parse(json.loads(line))
fhb.close()
fhOverall=codecs.open(outputDir+"overall_%s.tsv"%int(time.time()),"w","UTF-8")
fhOverall.write(Tweet.csvHeader())
for url in allTweets:
tweet=allTweets[url]
fhOverall.write(tweet.csvRow())
fhOverall.close()
logPrint("\nDONE! Completed Successfully")
fhLog.close()