-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathWhatsAppStats.py
315 lines (237 loc) · 9.15 KB
/
WhatsAppStats.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
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
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
#!/bin/env python
# -*- coding: utf-8 -*-
import re, datetime, string, csv
VERSION = 0.1
class User(object):
"""docstring for User"""
def __init__(self, name, globalStatistics):
self.name = name
self.messages = []
self.statistics = Statistics()
self.globalStatistics = globalStatistics
def addMsg(self, msg):
self.messages.append(msg)
self.lastMessage = len(self.messages) - 1
# local statistics
self.statistics.raiseMessageCount()
self.statistics.parseText(msg.text)
self.statistics.raiseTimeCount(msg.dTime.hour)
# global statistics
self.globalStatistics.raiseMessageCount()
self.globalStatistics.parseText(msg.text)
self.globalStatistics.raiseTimeCount(msg.dTime.hour)
def appendToLastMsg(self, text):
self.messages[self.lastMessage].text += text
def showMessages(self):
for msg in self.messages:
msg.printMessage()
class Statistics(object):
"""docstring for Statistics"""
def __init__(self):
self.reset()
def reset(self):
self.letters = {}
for char in string.ascii_lowercase:
self.letters[char] = 0
self.time = {}
for hour in range(24):
self.time[hour] = 0
self.words = {}
self.messages = 0
def raiseMessageCount(self):
self.messages += 1
def raiseTimeCount(self, hour):
self.time[hour] += 1
def parseText(self, text):
# Letter stats
for char in text:
if char in string.ascii_letters:
self.letters[char.lower()] += 1
textFormat = text.strip()
for word in textFormat.lower().split(" "):
if word in self.words:
self.words[word] += 1
else:
self.words[word] = 1
class Message(object):
"""docstring for Message"""
def __init__(self, sender, dTime, text):
self.sender = sender
self.dTime = dTime
self.text = text
def printMessage(self):
print "[" + str(self.dTime) + "] " + self.sender.name + ": " + self.text[:-1]
class WhatsAppStats(object):
"""docstring for WhatsAppStats"""
def __init__(self, inputFile):
self.file = inputFile
self.users = {}
self.globalStatistics = Statistics()
# Chronical order
self.chatMessages = []
def run(self):
# Read and parse the chatlog
f = open(self.file,'r')
for line in f.readlines():
self.parseLine(line)
f.close()
def printChat(self):
for msg in self.chatMessages:
msg.printMessage()
def printMessageCount(self):
count = 0
for user in self.users.values():
count += user.statistics.messages
print user.name + ": " + str(user.statistics.messages)
print "Total: " + str(count) + " messages"
def writeMessageCount(self):
fileToSave = 'WA_MessageCount.csv'
with open(fileToSave, 'wb') as csvfile:
writer = csv.writer(csvfile, dialect='excel', delimiter=';')
for user in self.users.values():
writer.writerow([user.name] + [str(user.statistics.messages)])
print "Wrote message count to " + fileToSave;
def printGlobalStat(self, statDict):
for key, value in statDict.items():
print str(key) + ": " + str(value)
def writeGlobalStat(self, statDict, filename):
with open(filename, 'wb') as csvfile:
writer = csv.writer(csvfile, dialect='excel', delimiter=';')
for key, value in statDict.items():
writer.writerow([key] + [str(value)])
def printLetterStats(self):
self.printGlobalStat(self.globalStatistics.letters);
def writeLetterStats(self):
fileToSave = 'WA_Letters.csv'
self.writeGlobalStat(self.globalStatistics.letters, fileToSave)
print "Wrote global letter stats to " + fileToSave;
def printLetterStatsPerUser(self):
for user in self.users.values():
print "\n" + user.name
for key, value in user.statistics.letters.items():
print key + ": " + str(value)
def writeLetterStatsPerUser(self):
fileToSave = 'WA_LettersPerUser.csv'
with open(fileToSave, 'wb') as csvfile:
writer = csv.writer(csvfile, dialect='excel', delimiter=';')
# Write names
writer.writerow([''] + [u.name for u in self.users.values()])
# Write letters
for letter in self.globalStatistics.letters.keys():
writer.writerow([letter] + [u.statistics.letters[letter] for u in self.users.values()])
print "Wrote letter stats per user to " + fileToSave;
def printTimeStats(self):
self.printGlobalStat(self.globalStatistics.time);
def writeTimeStats(self):
fileToSave = 'WA_Time.csv'
self.writeGlobalStat(self.globalStatistics.time, fileToSave)
print "Wrote global time stats to " + fileToSave;
def printTimeStatsPerUser(self):
for user in self.users.values():
print "\n" + user.name
for key, value in user.statistics.time.items():
print str(key) + ": " + str(value)
def writeTimeStatsPerUser(self):
fileToSave = 'WA_TimePerUser.csv'
with open(fileToSave, 'wb') as csvfile:
writer = csv.writer(csvfile, dialect='excel', delimiter=';')
# Write names
writer.writerow([''] + [u.name for u in self.users.values()])
# Write time
for time in self.globalStatistics.time.keys():
writer.writerow([time] + [u.statistics.time[time] for u in self.users.values()])
print "Wrote time stats per user to " + fileToSave;
def printWordsStats(self):
self.printGlobalStat(self.globalStatistics.words);
def writeWordsStats(self):
fileToSave = 'WA_Words.csv'
self.writeGlobalStat(self.globalStatistics.words, fileToSave)
print "Wrote global word stats to " + fileToSave;
def writeWordsStatsPerUser(self):
fileToSave = 'WA_WordsPerUser.csv'
with open(fileToSave, 'wb') as csvfile:
writer = csv.writer(csvfile, dialect='excel', delimiter=';')
# Write names
writer.writerow([''] + [u.name for u in self.users.values()])
# Write words
for word in self.globalStatistics.words.keys():
writer.writerow([word] + [u.statistics.words[word] if word in u.statistics.words else '0' for u in self.users.values()])
print "Wrote word stats per user to " + fileToSave;
def parseLine(self, line):
if line.strip() == "":
return
# Base from txt2re.com, can be optimized
re1='((?:(?:[0-2]?\\d{1})|(?:[3][01]{1}))[-:\\/.](?:[0]?[1-9]|[1][012])[-:\\/.](?:(?:\\d{1}\\d{1})))(?![\\d])' # DDMMYY 1
re2='.*?' # Non-greedy match on filler
re3='((?:(?:[0-1][0-9])|(?:[2][0-3])|(?:[0-9])):(?:[0-5][0-9])(?::[0-5][0-9])?(?:\\s?(?:am|AM|pm|PM))?)' # HourMinuteSec 1
re4='.*?' # Non-greedy match on filler
re5='[:\s]'
re6='(((?!:).)*)' # Sender
re8='[:\s]'
re9='((.*))'
rg = re.compile(re1+re2+re3+re4+re5+re6+re8+re9,re.IGNORECASE|re.DOTALL)
m = rg.search(line)
if m:
date = m.group(1)
time = m.group(2)
word1 = m.group(3)
text = m.group(5)
sender = word1.strip()
dTime = datetime.datetime.strptime(date + time, "%d.%m.%y%H:%M:%S")
##OTHER LANGUAGE? edit here:
# exclude some strings
if "trat bei" in sender or "wurde entfernt" in sender or "hat die Gruppe verlassen" in sender or "hat das Thema zu" in sender or "Du bist" in sender or "hat das Gruppen" in sender:
return
# add a new user
if not sender in self.users:
self.users[sender] = User(sender, self.globalStatistics)
tmpMsg = Message(self.users[sender], dTime, text)
self.users[sender].addMsg(tmpMsg)
self.chatMessages.append(tmpMsg)
self.lastUser = sender
else:
self.users[self.lastUser].appendToLastMsg(line)
if __name__ == '__main__':
import optparse
parser = optparse.OptionParser()
parser.usage = "%prog [options] file"
parser.version = 1
parser.description = ("Simple script to create some statistics from a WhatsApp group chat protocol")
parser.epilog = "Read the README for more info"
parser.add_option("-t", "--time", dest="time", help=("print time stats"), default=False, action="store_true")
parser.add_option("", "--timeUser", dest="timeUser", help=("print time stats per user"), default=False, action="store_true")
parser.add_option("-l", "--letter", dest="letter", help=("print letter stats"), default=False, action="store_true")
parser.add_option("", "--letterUser", dest="letterUser", help=("print letter stats per user"), default=False, action="store_true")
parser.add_option("-w", "--word", dest="word", help=("print word stats"), default=False, action="store_true")
parser.add_option("", "--wordUser", dest="wordUser", help=("print word stats per user"), default=False, action="store_true")
parser.add_option("-s", "--save", dest="save", help=("writes all statistics to different *.csv files. It's easy to import these in excel and create some barchars"), default=False, action="store_true")
(options, args) = parser.parse_args()
if len(args) != 1:
parser.print_usage()
exit()
print "\n=== WhatsAppStats v" + str(VERSION) + " ===\n"
chatStatistics = WhatsAppStats(args[0])
chatStatistics.run()
#chatStatistics.printChat()
if options.save:
chatStatistics.writeLetterStats()
chatStatistics.writeLetterStatsPerUser()
chatStatistics.writeTimeStats()
chatStatistics.writeTimeStatsPerUser()
chatStatistics.writeWordsStats()
chatStatistics.writeWordsStatsPerUser()
chatStatistics.writeMessageCount()
elif options.time:
chatStatistics.printTimeStats()
elif options.timeUser:
chatStatistics.printTimeStatsPerUser()
elif options.letter:
chatStatistics.printLetterStats()
elif options.letterUser:
chatStatistics.printLetterStatsPerUser()
elif options.word:
chatStatistics.printWordsStats()
elif options.wordUser:
chatStatistics.writeWordsStatsPerUser()
else:
chatStatistics.printMessageCount()