-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathquery_cqadupstack.py
1664 lines (1405 loc) · 82.6 KB
/
query_cqadupstack.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
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2015 Doris Hoogeveen (doris dot hoogeveen at gmail)
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os, re, sys
import nltk, json, codecs
import pydoc, math
import zipfile, random, datetime
import itertools
from operator import truediv
from scipy.misc import comb
from random import randrange
from HTMLParser import HTMLParser
# Written by Doris Hoogeveen Nov 2015. For a usage please call the script without arguments.
def load_subforum(subforumzipped):
''' Takes a subforum.zip file as input and returns a StackExchange Subforum class object.'''
return Subforum(subforumzipped)
class Subforum():
def __init__(self, zipped_catfile):
''' This class takes a StackExchange subforum.zip file as input and makes it queryable via the methods below. '''
# Check to see if supplied file exists and is a valid zip file.
if not os.path.exists(zipped_catfile):
sys.exit('The supplied zipfile does not exist. Please supply a valid StackExchange subforum.zip file.')
if not zipfile.is_zipfile(zipped_catfile):
sys.exit('Please supply a valid StackExchange subforum.zip file.')
self.cat = os.path.basename(zipped_catfile).split('.')[0]
self._unzip_and_load(zipped_catfile)
# Stopwords for cleaning. They need to be initialised here in case someone accesses self.stopwords.
self.__indri_stopwords = ['a', 'about', 'above', 'according', 'across', 'after', 'afterwards', 'again', 'against', 'albeit', 'all', 'almost', 'alone', 'along', 'already', 'also', 'although', 'always', 'am', 'among', 'amongst', 'an', 'and', 'another', 'any', 'anybody', 'anyhow', 'anyone', 'anything', 'anyway', 'anywhere', 'apart', 'are', 'around', 'as', 'at', 'av', 'be', 'became', 'because', 'become', 'becomes', 'becoming', 'been', 'before', 'beforehand', 'behind', 'being', 'below', 'beside', 'besides', 'between', 'beyond', 'both', 'but', 'by', 'can', 'cannot', 'canst', 'certain', 'cf', 'choose', 'contrariwise', 'cos', 'could', 'cu', 'day', 'do', 'does', "doesn't", 'doing', 'dost', 'doth', 'double', 'down', 'dual', 'during', 'each', 'either', 'else', 'elsewhere', 'enough', 'et', 'etc', 'even', 'ever', 'every', 'everybody', 'everyone', 'everything', 'everywhere', 'except', 'excepted', 'excepting', 'exception', 'exclude', 'excluding', 'exclusive', 'far', 'farther', 'farthest', 'few', 'ff', 'first', 'for', 'formerly', 'forth', 'forward', 'from', 'front', 'further', 'furthermore', 'furthest', 'get', 'go', 'had', 'halves', 'hardly', 'has', 'hast', 'hath', 'have', 'he', 'hence', 'henceforth', 'her', 'here', 'hereabouts', 'hereafter', 'hereby', 'herein', 'hereto', 'hereupon', 'hers', 'herself', 'him', 'himself', 'hindmost', 'his', 'hither', 'hitherto', 'how', 'however', 'howsoever', 'i', 'ie', 'if', 'in', 'inasmuch', 'inc', 'include', 'included', 'including', 'indeed', 'indoors', 'inside', 'insomuch', 'instead', 'into', 'inward', 'inwards', 'is', 'it', 'its', 'itself', 'just', 'kind', 'kg', 'km', 'last', 'latter', 'latterly', 'less', 'lest', 'let', 'like', 'little', 'ltd', 'many', 'may', 'maybe', 'me', 'meantime', 'meanwhile', 'might', 'moreover', 'most', 'mostly', 'more', 'mr', 'mrs', 'ms', 'much', 'must', 'my', 'myself', 'namely', 'need', 'neither', 'never', 'nevertheless', 'next', 'no', 'nobody', 'none', 'nonetheless', 'noone', 'nope', 'nor', 'not', 'nothing', 'notwithstanding', 'now', 'nowadays', 'nowhere', 'of', 'off', 'often', 'ok', 'on', 'once', 'one', 'only', 'onto', 'or', 'other', 'others', 'otherwise', 'ought', 'our', 'ours', 'ourselves', 'out', 'outside', 'over', 'own', 'per', 'perhaps', 'plenty', 'provide', 'quite', 'rather', 'really', 'round', 'said', 'sake', 'same', 'sang', 'save', 'saw', 'see', 'seeing', 'seem', 'seemed', 'seeming', 'seems', 'seen', 'seldom', 'selves', 'sent', 'several', 'shalt', 'she', 'should', 'shown', 'sideways', 'since', 'slept', 'slew', 'slung', 'slunk', 'smote', 'so', 'some', 'somebody', 'somehow', 'someone', 'something', 'sometime', 'sometimes', 'somewhat', 'somewhere', 'spake', 'spat', 'spoke', 'spoken', 'sprang', 'sprung', 'stave', 'staves', 'still', 'such', 'supposing', 'than', 'that', 'the', 'thee', 'their', 'them', 'themselves', 'then', 'thence', 'thenceforth', 'there', 'thereabout', 'thereabouts', 'thereafter', 'thereby', 'therefore', 'therein', 'thereof', 'thereon', 'thereto', 'thereupon', 'these', 'they', 'this', 'those', 'thou', 'though', 'thrice', 'through', 'throughout', 'thru', 'thus', 'thy', 'thyself', 'till', 'to', 'together', 'too', 'toward', 'towards', 'ugh', 'unable', 'under', 'underneath', 'unless', 'unlike', 'until', 'up', 'upon', 'upward', 'upwards', 'us', 'use', 'used', 'using', 'very', 'via', 'vs', 'want', 'was', 'we', 'week', 'well', 'were', 'what', 'whatever', 'whatsoever', 'when', 'whence', 'whenever', 'whensoever', 'where', 'whereabouts', 'whereafter', 'whereas', 'whereat', 'whereby', 'wherefore', 'wherefrom', 'wherein', 'whereinto', 'whereof', 'whereon', 'wheresoever', 'whereto', 'whereunto', 'whereupon', 'wherever', 'wherewith', 'whether', 'whew', 'which', 'whichever', 'whichsoever', 'while', 'whilst', 'whither', 'who', 'whoa', 'whoever', 'whole', 'whom', 'whomever', 'whomsoever', 'whose', 'whosoever', 'why', 'will', 'wilt', 'with', 'within', 'without', 'worse', 'worst', 'would', 'wow', 'ye', 'yet', 'year', 'yippee', 'you', 'your', 'yours', 'yourself', 'yourselves']
self.__short_stopwords = ['a', 'an', 'the', 'yes', 'no', 'thanks']
self.__middle_stopwords = ['in', 'on', 'at', 'a', 'an', 'is', 'be', 'was', 'I', 'you', 'the', 'do', 'did', 'of', 'so', 'for', 'with', 'yes', 'thanks']
# The NLTK stopwords cause a problem if they have not been downloaded, so we need a check for that.
try:
self.__nltk_stopwords = nltk.corpus.stopwords.words('english')
except:
self.__nltk_stopwords = []
self.__stopwords = self.__middle_stopwords # Default.
self.cutoffdate = False # Needed for classification splits.
def _unzip_and_load(self, zipped_catfile):
ziplocation = os.path.dirname(zipped_catfile)
cat = os.path.basename(zipped_catfile).split('.')[0]
questionfile = ziplocation + '/' + cat + '/' + cat + '_questions.json'
answerfile = ziplocation + '/' + cat + '/' + cat + '_answers.json'
commentfile = ziplocation + '/' + cat + '/' + cat + '_comments.json'
userfile = ziplocation + '/' + cat + '/' + cat + '_users.json'
if os.path.exists(questionfile) and os.path.exists(answerfile) and os.path.exists(userfile) and os.path.exists(commentfile):
pass # All good, we don't need to unzip anything
else:
zip_ref = zipfile.ZipFile(zipped_catfile, 'r')
zip_ref.extractall(ziplocation)
qf = codecs.open(questionfile, 'r', encoding='utf-8')
self.postdict = json.load(qf)
af = codecs.open(answerfile, 'r', encoding='utf-8')
self.answerdict = json.load(af)
cf = codecs.open(commentfile, 'r', encoding='utf-8')
self.commentdict = json.load(cf)
uf = codecs.open(userfile, 'r', encoding='utf-8')
self.userdict = json.load(uf)
print "Loaded all data from", zipped_catfile
def tokenize(self, s):
''' Takes a string as input, tokenizes it using NLTK (http://www.nltk.org) and returns a list of the tokens. '''
return nltk.word_tokenize(s) # The NLTK tokenizer cuts things like 'cannot' into 'can' and 'not'.
########################
# GENERAL POST METHODS #
########################
def get_posts_with_duplicates(self):
''' Takes no input and returns a list of all posts that have at least one duplicate. '''
dups = []
for p in self.postdict:
if len(self.postdict[p]['dups']) > 0:
dups.append(p)
return dups
def get_all_duplicate_pairs(self):
''' Takes no input an returns a list of duplicate question pairs as tuples of ids. '''
duppairs = []
for p in self.postdict:
for d in self.postdict[p]['dups']:
duppairs.append((p, d))
return duppairs
def get_posts_without_duplicates(self):
''' Takes no input and returns a list of all posts that don't have any duplicates. '''
nodups = []
for p in self.postdict:
if len(self.postdict[p]['dups']) == 0:
nodups.append(p)
return nodups
def get_posts_with_related(self):
''' Takes no input and returns a list of all posts that have related questions. '''
related = []
for p in self.postdict:
if len(self.postdict[p]['related']) > 0:
related.append(p)
return related
def get_all_related_pairs(self):
''' Takes no input an returns a list of related question pairs as tuples of ids. '''
relpairs = []
for p in self.postdict:
for d in self.postdict[p]['related']:
relpairs.append((p, d))
return relpairs
def get_posts_with_and_without_duplicates(self):
''' Takes no input and returns two lists: one with all posts that have at least one duplicate, and one with all posts that don't have any duplicates. In that order.
Calling this method is quicker than calling get_posts_with_duplicates() followed by get_posts_without_duplicates() if you want both dups and non-dups. '''
nodups = []
dups = []
for p in self.postdict:
if len(self.postdict[p]['dups']) == 0:
nodups.append(p)
else:
dups.append(p)
return dups, nodups
def get_posts_dups_nodups_and_related(self):
''' Takes no input and return three lists: one with all posts that have at least one duplicate, one with all posts that have at least one related question, and one with all posts that don't have any duplicates or related questions. In that order.
Calling this method is quicker than calling get_posts_with_duplicates(), followed by get_posts_with_related(), followed by get_posts_without_duplicates() if you want all three types of questions.
There may be overlap in the list of posts with duplicates and posts with related questions, because posts can have bot duplicates and related questions. '''
nodups = []
dups = []
related = []
for p in self.postdict:
if len(self.postdict[p]['dups']) == 0 and len(self.postdict[p]['related']) == 0:
nodups.append(p)
if len(self.postdict[p]['related']) > 0:
related.append(p)
if len(self.postdict[p]['dups']) > 0:
dups.append(p)
return dups, related, nodups
def get_older_posts(self, postid):
''' Takes a post id as input and returns a list of question ids that are older than the input post id. '''
allordered = [i[0] for i in self.get_ordered_list_of_posts()]
postindex = allordered.index(postid)
return allordered[postindex:]
def get_ordered_list_of_posts(self):
''' Takes no input and returns a list of tuples (postid, datetime object), ordered chronologically from newest to oldest post. '''
return sorted([(i, datetime.datetime.strptime(self.get_postdate(i), '%Y-%m-%d')) for i in self.postdict], key=lambda x: x[1], reverse=True)
def get_random_postid(self):
''' Takes no input and returns a random post id. '''
allids = self.postdict.keys()
return random.choice(allids)
def get_random_pair_of_posts(self):
''' Takes no input and returns a tuple with two random post ids and a duplicate verdict. The second is always lower than the first.
Example: (4865, 553, 'dup')
Other values for the verdict are: 'related' and 'nondup'. '''
allids = self.postdict.keys()
id1 = random.choice(allids)
id2 = random.choice(allids)
while id2 >= id1:
id2 = random.choice(allids)
if id2 in self.postdict[id1]['dups']:
return (id1, id2, 'dup')
elif id2 in self.postdict[id1]['related']:
return (id1, id2, 'related')
else:
return (id1, id2, 'nondup')
def get_all_postids(self):
''' Takes no input and returns a list of ALL post ids. '''
return self.postdict.keys()
def get_true_label(self, postid1, postid2):
''' Takes two postids as input and returns the true label, which is one of "dup", "nodup" or "related". '''
if postid1 in self.postdict[postid2]['dups']:
return "dup"
elif postid1 in self.postdict[postid2]['related']:
return "related"
elif postid2 in self.postdict[postid1]['dups']:
return "dup"
elif postid2 in self.postdict[postid1]['related']:
return "related"
else:
return "nodup"
###########################
# PARTICULAR POST METHODS #
###########################
def get_posttitle(self, postid):
''' Takes a post id as input and returns the title of the post. '''
return self.postdict[postid]["title"]
def get_postbody(self, postid):
''' Takes a post id as input and returns the body of the post. '''
return self.postdict[postid]["body"]
def get_post_title_and_body(self, postid):
''' Takes a post id as input and returns the title and the body of the post together as one string, so in other words, the full initial post. '''
t = self.postdict[postid]["title"]
b = self.postdict[postid]["body"]
return t + ' ' + b
def get_postdate(self, postid):
''' Takes a post id as input and returns the date the post was posted in YYYY-MM-DD format. '''
cdate = datetime.datetime.strptime(self.postdict[postid]['creationdate'], "%Y-%m-%dT%H:%M:%S.%f")
return str(cdate.year) + '-' + cdate.strftime('%m') + '-' + cdate.strftime('%d')
def get_posttime(self, postid):
''' Takes a post id as input and returns the time the post was posted in HH:MM:SS format. '''
cdate = datetime.datetime.strptime(self.postdict[postid]['creationdate'], "%Y-%m-%dT%H:%M:%S.%f")
return cdate.strftime('%H') + ':' + cdate.strftime('%M') + ':' + cdate.strftime('%S')
def get_postviewcount(self, postid):
''' Takes a post id as input and returns the number of times the post has been looked at by users. '''
return self.postdict[postid]["viewcount"]
def get_postfavoritecount(self, postid):
''' Takes a post id as input and returns an integer representing the nr of times this post has been favoured by a user.
More information on what that means can be found here: http://meta.stackexchange.com/questions/53585/how-do-favorite-questions-work '''
return self.postdict[postid]['favoritecount']
def get_postscore(self, postid):
''' Takes a post id as input and returns the score of the post. This is the number of upvotes minus the number of downvotes is has received. '''
return self.postdict[postid]['score']
def get_postuserid(self, postid):
''' Takes a post id as input and returns the userid of the person that posted it. Returns False if the user is not known. '''
return self.postdict[postid]['userid']
def get_duplicates(self, postid):
''' Takes a post id as input and returns a list of ids of posts that have been labeled as a duplicate of it. '''
return self.postdict[postid]['dups']#.keys()
def get_related(self, postid):
''' Takes a post id as input and returns a list of ids of posts that have been labeled as related to it. '''
return self.postdict[postid]['related']
def get_posttags(self, postid):
''' Takes a post id as input and returns a list of tags. '''
return self.postdict[postid]['tags']
def get_duptagdates(self, postid1, postid2):
''' Takes two post ids as input and returns a list of dates on which this pair received a duplicate tag, in %Y-%m-%dT%H:%M:%S.%f format.
Usually the list only contains one date, but sometimes it contains multiple. '''
if postid1 in self.postdict[postid2]['dups']:
ddates_raw = self.postdict[postid2]['dups'][postid1]['votedates']
else:
ddates_raw = self.postdict[postid1]['dups'][postid2]['votedates']
ddates = []
for ddate in ddates_raw:
#datet = datetime.datetime.strptime(ddate, "%Y-%m-%dT%H:%M:%S.%f")
#dates.append(str(datet.year) + '-' + datet.strftime('%m') + '-' + datet.strftime('%d'))
ddates.append(ddate)
return ddates
def get_first_duptagdate(self, postid):
''' Takes one postid as input and returns the date on which this post was tagged as a duplicate for the first time, in %Y-%m-%dT%H:%M:%S.%f format,
or 0 if the post has not been tagged as a duplicate (yet). '''
dups = self.get_duplicates(postid)
dupdates = []
for dup in dups:
checkdates = self.postdict[postid]['dups'][dup]['votedates']
for c in checkdates:
cdate = datetime.datetime.strptime(c, "%Y-%m-%dT%H:%M:%S.%f")
dupdates.append(c)
dupdates.sort()
#print dupdates
if len(dupdates) > 0:
return dupdates[0]
else:
0
def get_dupvoters(self, postid1, postid2):
''' Takes two post ids as input and returns a list of the users that have voted for these two questions to be duplicates. '''
if postid1 in self.postdict[postid2]['dups']:
return self.postdict[postid2]['dups'][postid1]['voters']
else:
return self.postdict[postid1]['dups'][postid2]['voters']
##################
# ANSWER METHODS #
##################
def get_answers(self, postid):
''' Takes a post id as input and returns a list of answer ids. '''
return self.postdict[postid]["answers"]
def get_answercount(self, postid):
''' Takes a post id as input and returns an integer representing the number of answers it has received. '''
return len(self.postdict[postid]['answers'])
def get_answer_parentid(self, answerid):
''' Takes an answer id as input and returns its parent id: the id of the post it is an answer of. '''
return self.answerdict[answerid]['parentid']
def get_acceptedanswer(self, postid):
''' Takes a post id as input and returns the answer id of the accepted answer if it exists, else it returns False. '''
if postid not in self.postdict:
raise KeyError(postid + " is not a valid post id for this subforum.")
if 'acceptedanswer' in self.postdict[postid]:
return self.postdict[postid]['acceptedanswer']
else:
return False
def get_acceptedanswer_date(self, answerid):
''' Takes an answer id as input and returns the date at which it was selected as the best answer in YYYY-MM-DD format, if it exists. Else it returns 0. '''
if self.answerdict[answerid]['acceptedanswerdate'] == 0:
return 0
else:
adate = datetime.datetime.strptime(self.answerdict[answerid]['acceptedanswerdate'], "%Y-%m-%dT%H:%M:%S.%f")
return str(adate.year) + '-' + adate.strftime('%m') + '-' + adate.strftime('%d')
def get_answerbody(self, answerid):
''' Takes an answer id as input and returns the body of the answer. That is the text of the answer. '''
return self.answerdict[answerid]['body']
def get_answerdate(self, answerid):
''' Takes an answer id as input and returns the date the answer was posted in YYYY-MM-DD format. '''
cdate = datetime.datetime.strptime(self.answerdict[answerid]['creationdate'], "%Y-%m-%dT%H:%M:%S.%f")
return str(cdate.year) + '-' + cdate.strftime('%m') + '-' + cdate.strftime('%d')
def get_answertime(self, answerid):
''' Takes an answer id as input and returns the time the answer was posted in HH:MM:SS format. '''
cdate = datetime.datetime.strptime(self.answerdict[answerid]['creationdate'], "%Y-%m-%dT%H:%M:%S.%f")
return cdate.strftime('%H') + ':' + cdate.strftime('%M') + ':' + cdate.strftime('%S')
def get_answerscore(self, answerid):
''' Takes an answer id as input and returns an integer representing the score of the answer. This is the number of upvotes minus the number of downvotes is has received. '''
return self.answerdict[answerid]["score"]
def get_answeruserid(self, answerid):
''' Takes an answer id as input and returns the userid of the person that posted it. Returns False if the user is not known. '''
return self.answerdict[answerid]['userid']
###################
# COMMENT METHODS #
###################
def get_post_comments(self, postid):
''' Takes a post id as input and returns a list of comment ids. '''
return self.postdict[postid]['comments']
def get_answer_comments(self, answerid):
''' Takes an answer id as in put and returns a list of comment ids. '''
return self.answerdict[answerid]['comments']
def get_post_commentcount(self, postid):
''' Takes a post id as input and returns and integer representing the number of comments this post has received. '''
return len(self.postdict[postid]['comments'])
def get_answer_commentcount(self, answerid):
''' Takes an answer id as input and returns and integer representing the number of comments this answer has received. '''
return len(self.answerdict[answerid]['comments'])
def get_comment_parentid(self, commentid):
''' Takes a comment id as input and returns its parent id: the id of the post or answer it is a comment to. '''
return self.commentdict[commentid]['parentid']
def get_comment_parenttype(self, commentid):
''' Takes a comment id as input and returns either 'question' or 'answer', depending on the type of its parent id. '''
return self.commentdict[commentid]['parenttype']
def get_commentbody(self, commentid):
''' Takes a comment id as input and returns the body of the comment. '''
return self.commentdict[commentid]['body']
def get_commentdate(self, commentid):
''' Takes a comment id as input and returns the date the comment was posted, in YYYY-MM-DD format. '''
cdate = datetime.datetime.strptime(self.commentdict[commentid]['creationdate'], "%Y-%m-%dT%H:%M:%S.%f")
return str(cdate.year) + '-' + cdate.strftime('%m') + '-' + cdate.strftime('%d')
def get_commenttime(self, commentid):
''' Takes a comment id as input and returns the time the comment was posted, in HH:MM:SS format. '''
cdate = datetime.datetime.strptime(self.commentdict[commentid]['creationdate'], "%Y-%m-%dT%H:%M:%S.%f")
return cdate.strftime('%H') + ':' + cdate.strftime('%M') + ':' + cdate.strftime('%S')
def get_commentscore(self, commentid):
''' Takes a comment id as input and returns an integer representing the score of the comment. This is the number of upvotes minus the number of downvotes is has received. '''
return self.commentdict[commentid]['score']
def get_commentuserid(self, commentid):
''' Takes a comment id as input and returns the id of the user that posted the comment. '''
return self.commentdict[commentid]['userid']
################
# USER METHODS #
################
def get_all_users(self):
''' Takes no input and returns a list of all users. '''
return self.userdict.keys()
def get_user_reputation(self, userid):
''' Takes a user id as input and outputs an integer representing the reputation of the user.
Information on what this means and how it is calculated can be found here http://stackoverflow.com/help/whats-reputation '''
return self.userdict[userid]['rep']
def get_user_views(self, userid):
''' Takes a user id as input and outputs an integer representing how often people have viewed a post by this user. '''
return self.userdict[userid]['views']
def get_user_upvotes(self, userid):
''' Takes a user id as input and outputs an integer representing how many upvotes on posts or answers this user has received. '''
return self.userdict[userid]['upvotes']
def get_user_downvotes(self, userid):
''' Takes a user id as input and outputs an integer representing how many downvotes on posts or answers this user has received. '''
return self.userdict[userid]['downvotes']
def get_user_joindate(self, userid):
''' Takes a user id as input and outputs the date this user joined this subforum, in YYYY-MM-DD format. '''
cdate = datetime.datetime.strptime(self.userdict[userid]['date_joined'], "%Y-%m-%dT%H:%M:%S.%f")
return str(cdate.year) + '-' + cdate.strftime('%m') + '-' + cdate.strftime('%d')
def get_user_lastaccess(self, userid):
''' Takes a user id as input and outputs the last time this user has logged into this subforum, in YYYY-MM-DD format. '''
cdate = datetime.datetime.strptime(self.userdict[userid]['lastaccessdate'], "%Y-%m-%dT%H:%M:%S.%f")
return str(cdate.year) + '-' + cdate.strftime('%m') + '-' + cdate.strftime('%d')
def get_user_age(self, userid):
''' Takes a user id as input and outputs the user's age as an integer, if known. Else it returns 'unknown'. '''
if 'age' in self.userdict[userid]:
return self.userdict[userid]['age']
else:
return 'unknown'
def get_user_posts(self, userid):
''' Takes a user id as input and returns a list of the question posts he/she has made. '''
return self.userdict[userid]['questions']
def get_user_answers(self, userid):
''' Takes a user id as input and returns a list of the answers he/she has written. '''
return self.userdict[userid]['answers']
def get_user_badges(self, userid):
''' Takes a user id as input and returns a list of the badges this user has earned.
Information on what badges are and which ones can be earned can be found here: http://stackoverflow.com/help/badges '''
return self.userdict[userid]['badges']
####################
# Cleaning methods #
####################
@property
def stopwords(self):
''' Returns the current list of words that is used as the stop word list. It can be accessed via self.stopwords'''
return self.__stopwords
def supply_stopwords(self, filename):
''' Takes as input a plain text file encoded in UTF-8 with one stop word per line and saves these internally in a stop word list.
This list will be used in cleaning if perform_cleaning() is called with remove_stopwords=True. '''
self.__stopwords = []
inputf_open = codecs.open(filename, 'r', encoding='utf-8')
inputf = inputf_open.readlines()
inputf_open.close()
for line in inputf:
line = line.rstrip()
self.__stopwords.append(line)
def change_to_default_stopwords(self, stopwordset='middle'):
''' Changes the stopword list to one of the supplied ones: 'nltk', 'indri', 'short' or 'middle'. 'Middle' is the default.
The NLTK stopword list contains 127 stopwords. (http://www.nltk.org/book/ch02.html#code-unusual)
The Indri stopword list contains 418 stopwords. (http://www.lemurproject.org/stopwords/stoplist.dft)
Short = ["a", "an", "the", "yes", "no", "thanks"]
Middle = ["in", "on", "at", "a", "an", "is", "be", "was", "I", "you", "the", "do", "did", "of", "so", "for", "with", "yes", "thanks"]
To be able to use the NLTK stopwords, they need to be downloaded first. See: http://www.nltk.org/data.html for more info.
If the data is not downloaded first, the script will default to the NLTK stopword list of November 2015.
'''
if stopwordset == 'nltk':
if self.__nltk_stopwords != []:
self.__stopwords = self.__nltk_stopwords
else: # This can happen if the NLTK stopwords have not been downloaded yet. Defaulting to the NLTK stopword list of November 2015.
self.__stopwords = [u'i', u'me', u'my', u'myself', u'we', u'our', u'ours', u'ourselves', u'you', u'your', u'yours', u'yourself', u'yourselves', u'he', u'him', u'his', u'himself', u'she', u'her', u'hers', u'herself', u'it', u'its', u'itself', u'they', u'them', u'their', u'theirs', u'themselves', u'what', u'which', u'who', u'whom', u'this', u'that', u'these', u'those', u'am', u'is', u'are', u'was', u'were', u'be', u'been', u'being', u'have', u'has', u'had', u'having', u'do', u'does', u'did', u'doing', u'a', u'an', u'the', u'and', u'but', u'if', u'or', u'because', u'as', u'until', u'while', u'of', u'at', u'by', u'for', u'with', u'about', u'against', u'between', u'into', u'through', u'during', u'before', u'after', u'above', u'below', u'to', u'from', u'up', u'down', u'in', u'out', u'on', u'off', u'over', u'under', u'again', u'further', u'then', u'once', u'here', u'there', u'when', u'where', u'why', u'how', u'all', u'any', u'both', u'each', u'few', u'more', u'most', u'other', u'some', u'such', u'no', u'nor', u'not', u'only', u'own', u'same', u'so', u'than', u'too', u'very', u's', u't', u'can', u'will', u'just', u'don', u'should', u'now']
elif stopwordset == 'indri':
self.__stopwords = self.__indri_stopwords
elif stopwordset == 'short':
self.__stopwords = self.__short_stopwords
else:
self.__stopwords = self.__middle_stopwords # DEFAULT
def perform_cleaning(self, s, maxcodelength=150, remove_stopwords=False, remove_punct=False, stem=False):
''' Takes a string as input and returns a cleaned version.
- The string will be lowercased and newlines removed.
- HTML tags will be removed.
- Mentions of possible duplicates will be removed.
- URLs pointing to other StackExchange threads are turned into 'stackexchange-url'.
- Blocks of code will be removed.
- Contracted forms will be expanded. E.g. "didn't" --> "did not".
- '&' will be turned into 'and'.
- Other HTML entities will be removed, and string matching the following pattern too: '&#?[a-z]+;'.
- Whitespace is added around punctuation
OPTIONAL ARGUMENTS:
maxcodelength: the maximum length of code blocks that will not be removed. Default: 150.
remove_stopwords: removed stop words. (Values: True or False)
remove_punct: punctuation is removed, except for punctuation in URLs and numbers. (Values: True or False)
stem: stemming is performed via the Porter stemmer as implemented in the NLTK (http://www.nltk.org/). (Values: True or False)
'''
s, codes = self._deal_with_code(s,maxcodelength)
s = s.lower()
s = re.sub('\n', ' ', s)
s = self._remove_tags(s)
s = self._expand_contractions(s)
s = self._general_cleaning(s,codes,remove_punct)
if remove_stopwords:
s = self._remove_stopwords(s)
if stem:
s = self._stem(s)
s = self._fix_exceptions(s)
# TODO: consider removing dashes between hyphenated words (far-off -> faroff), and removing full stops in acronyms/initials (U.N. -> UN). It helps for METEOR apparently (http://www.cs.cmu.edu/~alavie/METEOR/pdf/meteor-wmt11.pdf). U.S.-based will become US based.
return s
def _fix_exceptions(self, s):
''' Takes a string as input, applies a bunch of regexes to it to fix exceptions that have accidentally been changed, and returns the new string. '''
s = re.sub(' \. net ', ' .net', s)
s = re.sub(' i \. e ', ' i.e. ', s)
# fix extensions
s = re.sub(' \. jpeg ', '.jpeg ', s)
s = re.sub(' \. jpg ', '.jpg ', s)
return s
def _deal_with_code(self, s, maxcodelength):
''' Takes a string as input, finds all code blocks in it and replace them with HHHH to protect them from whitespace addition, lower casing etc. Then returns the new string and a list of the code blocks so we can replace them after more cleaning. '''
codepat = re.compile(r'<code>[^<]+</code>')
codes = re.findall(codepat, s) # re.M for multiline matching not necessary?
n = 0
newcodes = []
for c in codes:
if len(c) < maxcodelength + 13: # two code tags are 13 characters
s = re.sub(re.escape(c), 'HHHH' + str(n), s)
# Remove brackets if other half is missing. Else we'll have problems when we try to put them back.
if re.search(r'\)', c) and not re.search(r'\(', c):
c = re.sub(r'\)', '', c)
if re.search(r'\(', c) and not re.search(r'\)', c):
c = re.sub(r'\(', '', c)
c = re.sub(r'\n', ' ', c, re.M) # remove real newlines
c = re.sub(r'\\n', r'\\\\n', c) # keep and escape \n in things like latex's \newcommand{}.
c = re.sub(r'\s+', ' ', c)
c = re.sub(r'<code>', '', c)
c = re.sub(r'</code>', '', c)
newcodes.append(c)
n += 1
else:
s = re.sub(re.escape(c), '', s) # Remove large code blocks
return s, newcodes
def very_basic_cleaning(self, s):
s = self.url_cleaning(s)
s = self.strip_tags(s)
s = ' '.join(s.split()) # remove multiple whitespaces
s = re.sub('\n+', ' ', s)
return s
def url_cleaning(self, s):
''' Takes a string as input and removes references to possible duplicate posts, and other stackexchange urls. '''
posduppat = re.compile(r'<blockquote>(.|\n)+?Possible Duplicate(.|\n)+?</blockquote>', re.MULTILINE)
s = re.sub(posduppat, '', s)
s = re.sub(r'<a[^>]+stackexchange[^>]+>([^<]+)</a>', r'stackexchange-url ("\1")', s)
s = re.sub(r'<a[^>]+stackoverflow[^>]+>([^<]+)</a>', r'stackexchange-url ("\1")', s)
return s
def strip_tags(self, html): # Source: http://stackoverflow.com/questions/753052/strip-html-from-strings-in-python
s = MLStripper()
s.feed(html)
return s.get_data()
def _remove_stopwords(self, s):
''' Takes a string as input, removes the stop words in the current stop word list, and returns the result.
The current stop word list can be accessed via self.stopwords, or altered by calling supply_stopwords(). '''
words = nltk.word_tokenize(s) # The NLTK tokenizer cuts things like 'cannot' into 'can' and 'not'.
words_split = s.split()
if 'cannot' in words_split: # which we'd like to keep.
location = words_split.index('cannot')
words_split[location] = 'can'
words_split.insert(location + 1, 'not')
counter = 0
filteredwords = []
prevw_in_split = True
for w in words:
# It used to be so beautifully simple, until I found out NLTK sometimes splits things wrongly.
#if w in self.__stopwords:
# pass # skip it, we don't want it.
#else:
# filteredwords.append(w)
if words_split[counter] == w: # word was correctly split
if w not in self.__stopwords:
filteredwords.append(w)
counter += 1
prevw_in_split = True
elif prevw_in_split: # previous word was fine, but this is the first part of a wrongly split word.
filteredwords.append(w)
prevw_in_split = False
else: # this is a subsequent part of a wrongly split word
newword = filteredwords[-1] + w
filteredwords[-1] = newword
if words_split[counter] == newword:
counter += 1
prevw_in_split = True
else:
prevw_in_split = False
cleanstring = ' '.join(filteredwords)
cleanstring = self._fix_abbreviations(cleanstring)
return cleanstring
def _stem(self, s):
''' Takes a string as input and applies the Porter stemmer as implemented in the NLTK (http://www.nltk.org/). Returns the result. '''
words = nltk.word_tokenize(s)
words_split = s.split()
if 'cannot' in words_split:
location = words_split.index('cannot')
words_split[location] = 'can'
words_split.insert(location + 1, 'not')
counter = 0
newwords = []
prevw_in_split = True
for w in words:
# It used to be so beautiful and simple, until I found out that NLTK splits some things wrongly...
#neww = nltk.PorterStemmer().stem_word(w)
#newwords.append(neww)
if words_split[counter] == w: # word was correctly split
neww = nltk.PorterStemmer().stem_word(w)
newwords.append(neww)
counter += 1
prevw_in_split = True
elif prevw_in_split: # previous word was fine, but this is the first part of a wrongly split word.
newwords.append(w)
prevw_in_split = False
else: # this is a subsequent part of a wrongly split word
newword = newwords[-1] + w
if words_split[counter] == newword:
newwords[-1] = nltk.PorterStemmer().stem_word(newword)
counter += 1
prevw_in_split = True
else:
newwords[-1] = newword
prevw_in_split = False
news = ' '.join(newwords)
news = self._fix_abbreviations(news)
return news
def _fix_abbreviations(self, s):
''' Takes as input a string tokenized by nltk and joined again, and outputs a version in which the abbreviations have been fixed.
That means the final dot has been glued to the abbreviation once more.'''
if re.search(r' ([a-z]\.[a-z])+ \.', s):
found = re.search(r'( ([a-z]\.[a-z])+ \.)', s)
abbr = found.group(1)
newabbr = re.sub(' ', '', abbr)
s = re.sub(abbr, ' ' + newabbr, s)
return s
def _remove_tags(self, s):
''' Takes a string as input and removes HTML tags, except for code tags, which are remove in general_cleaning.
Also removes mentions of possible duplicates and changes URLs that point to other StackExchange threads into 'stackexahcnge-url'. '''
s = re.sub(r"<blockquote.+possible duplicate.+/blockquote>", " ", s)
s = re.sub(r"<a href=\"https?://[a-z]+\.stackexchange\.com[^\"]+\">([^<]+)</a>", r"\1", s)
s = re.sub(r"<a href=\"[^\"]+\">([^<]+)</a>", r"\1", s)
# Put some space between tags and urls or other things. So we don't accidentally remove more than we should a few lines further below this line.
s = re.sub(r"<", " <", s)
s = re.sub(r">", "> ", s)
s = re.sub(r"https?://([a-z]+\.)?stackexchange\.com[^ ]+", "stackexchange-url", s)
s = re.sub(r"https?://stackoverflow\.com[^ ]+", "stackexchange-url", s)
# Remove all tags except for code tags
alltags = re.findall(r'(</?)([^>]+)(>)', s) # list of tuples
for tag in alltags:
if tag[1] != u'code':
codetag = tag[0] + tag[1] + tag[2]
s = re.sub(re.escape(codetag), '', s)
return s
def _expand_contractions(self, s):
''' Takes a string as input, expands the contracted forms in it and returns the result. '''
# Source: http://www.englishcoursemalta.com/learn/list-of-contracted-forms-in-english/
c = {'i\'m': 'i am',
'you\'re': 'you are',
'he\'s': 'he is',
'she\'s': 'she is',
'we\'re': 'we are',
'it\'s': 'it is',
'isn\'t': 'is not',
'aren\'t': 'are not',
'they\'re': 'they are',
'there\'s': 'there is',
'wasn\'t': 'was not',
'weren\'t': ' were not',
'i\'ve': 'i have',
'you\'ve': 'you have',
'we\'ve': 'we have',
'they\'ve': 'they have',
'hasn\'t': 'has not',
'haven\'t': 'have not',
'you\'d': 'you had',
'he\'d': 'he had',
'she\'d': 'she had',
'we\'d': 'we had',
'they\'d': 'they had',
'doesn\'t': 'does not',
'don\'t': 'do not',
'didn\'t': 'did not',
'i\'ll': 'i will',
'you\'ll': 'you will',
'he\'ll': 'he will',
'she\'ll': 'she will',
'we\'ll': 'we will',
'they\'ll': 'they will',
'there\'ll': 'there will',
'i\'d': 'i would',
'it\'d': 'it would',
'there\'d': 'there had',
'there\'d': 'there would',
'can\'t': 'can not',
'couldn\'t': 'could not',
'daren\'t': 'dare not',
'hadn\'t': 'had not',
'mightn\'t': 'might not',
'mustn\'t': 'must not',
'needn\'t': 'need not',
'oughtn\'t': 'ought not',
'shan\'t': 'shall not',
'shouldn\'t': 'should not',
'usedn\'t': 'used not',
'won\'t': 'will not',
'wouldn\'t': 'would not',
'what\'s': 'what is',
'that\'s': 'that is',
'who\'s': 'who is',}
# Some forms of 's could either mean 'is' or 'has' but we've made a choice here.
# Some forms of 'd could either mean 'had' or 'would' but we've made a choice here.
# Some forms of 'll could wither mean 'will' or 'shall' but we've made a choice here.
for pat in c:
s = re.sub(pat, c[pat], s)
return s
def _general_cleaning(self, s, codes, remove_punct=False):
''' Takes a string as input and False or True for the argument 'remove_punct'.
Depending on the value of 'remove_punct', all punctuation is either removed, or a space is added before and after.
In both cases the punctuation un URLs and numbers is retained.
Also transforms "&" into "and", and removes all other HTML entities.
Removes excessive white space. '''
# Find all URLs and replace them with GGGG to protect them from whitespace addition.
urlpat = re.compile(r'https?://[^ ]+')
wwwpat = re.compile(r'www\.[^ ]+')
compat = re.compile(r'[^ ]+\.com[^ ]+')
coms = re.findall(compat, s)
wwws = re.findall(wwwpat, s)
urls = re.findall(urlpat, s)
urls += wwws + coms
n = 0
newurls = []
for url in set(urls):
if re.search(r'\)', url) and not re.search('\(', url):
url = re.sub(r'\).*$', '', url)
if re.search(r'\\', url): # Get rid of backslashes because else we get regex problems when trying to put the URLs back.
url = re.sub(r'\\', '/', url)
s = re.sub(re.escape(url), 'GGGG' + str(n), s)
newurls.append(url)
n += 1
# Protect points, commas and colon in numbers
while re.search(r'([0-9])\.([0-9])', s):
s = re.sub(r'([0-9])\.([0-9])', r'\1BBB\2', s)
while re.search(r'([0-9]),([0-9])', s):
s = re.sub(r'([0-9]),([0-9])', r'\1CCC\2', s)
while re.search(r'([0-9]):([0-9])', s):
s = re.sub(r'([0-9]):([0-9])', r'\1DDD\2', s)
s = re.sub(r'&', ' and ', s)
if remove_punct:
# Remove all sorts of punctuation
#s = re.sub('[^a-zA-Z0-9_-]', ' ', s) # Too agressive!
p = re.compile(r'( [a-z] \.)( [a-z] \.)+')
l = p.finditer(s)
if l:
for m in l:
newbit = re.sub(r' ', '', m.group()) # Get rid of white space in abbreviations
newabbr = re.sub(r'\.', 'PPPP', newbit) # change dots in abbreviations into 'PPPP'
s = re.sub(m.group() + ' +', ' ' + newabbr + ' ', s) # protect abbreviations
s = re.sub(r'\.', '', s) # remove all points that are not in abbreviations
s = re.sub(newabbr, newbit, s) # place dots back in abbreviations
else:
s = re.sub(r'\.', ' ', s)
s = re.sub(r',', ' ', s)
s = re.sub(r'\?', ' ', s)
s = re.sub(r'!', ' ', s)
s = re.sub(r' \'([a-z])', r' \1', s)
s = re.sub(r'([a-z])\' ', r'\1 ', s)
s = re.sub(r' \"([a-z])', r' \1', s)
s = re.sub(r'([a-z])\" ', r'\1 ', s)
s = re.sub(r'\(', ' ', s)
s = re.sub(r'\)', ' ', s)
s = re.sub(r'\[', ' ', s)
s = re.sub(r'\]', ' ', s)
s = re.sub(r'([a-z]): ', r'\1 ', s)
s = re.sub(r';', ' ', s)
s = re.sub(r" - ", " ", s)
s = re.sub(r"- ", " ", s)
s = re.sub("`", "", s)
s = re.sub('“', '', s)
s = re.sub('”', '', s)
s = re.sub('"', '', s)
else:
# Add space around all sorts of punctuation.
#s = re.sub('([^a-zA-Z0-9_-])', r' \1 ', s) # Too agressive!
s = re.sub(r'\.', ' . ', s)
# Remove space around abbreviations
p = re.compile(r'( [a-z] \.)( [a-z] \.)+')
for m in p.finditer(s):
#print m.start(), '###' + m.group() + '###'
#print s[m.start() - 20: m.start() + 20]
newbit = re.sub(' ', '', m.group())
s = re.sub(m.group() + ' +', ' ' + newbit + ' ', s)
#print s[m.start() - 20: m.start() + 20]
s = re.sub(r',', ' , ', s)
s = re.sub(r'\?', ' ? ', s)
s = re.sub(r'!', ' ! ', s)
s = re.sub(r' \'([a-z])', r" ' \1", s)
s = re.sub(r'([a-z])\' ', r"\1 ' ", s)
s = re.sub(r' \"([a-z])', r' " \1', s)
s = re.sub(r'([a-z])\" ', r'\1 " ', s)
s = re.sub(r'\(', ' ( ', s)
s = re.sub(r'\)', ' ) ', s)
s = re.sub(r'\[', ' [ ', s)
s = re.sub(r'\]', ' ] ', s)
s = re.sub(r'([a-z]): ', r'\1 : ', s)
s = re.sub(r';', ' ; ', s)
s = re.sub(r"'s", " 's", s)
# Restore points, commas and colons in numbers
while re.search(r'([0-9])BBB([0-9])', s):
s = re.sub(r'([0-9])BBB([0-9])', r'\1.\2', s)
while re.search(r'([0-9])CCC([0-9])', s):
s = re.sub(r'([0-9])CCC([0-9])', r'\1,\2', s)
while re.search(r'([0-9])DDD([0-9])', s):
s = re.sub(r'([0-9])DDD([0-9])', r'\1:\2', s)
# restore URLs
newurllist = itertools.izip(reversed(xrange(len(newurls))), reversed(newurls)) # reverse list to GGGG1 does not match GGG10. (Source: http://galvanist.com/post/53478841501/python-reverse-enumerate)
for i, u in newurllist:
s = re.sub('GGGG' + str(i), u, s) # Escaping u here leads to backslashes in URLs.
# Get rid of things we don't want, like HTML entities.
s = re.sub(r"&[a-z]+;", "", s)
s = re.sub(r"&#?[a-z]+;", "", s) # 
 == '\n'
# Remove excessive whitespace
s = re.sub(r"\s+", " ", s)
s = re.sub(r"^\s", "", s)
s = re.sub(r"\s$", "", s)
# restore codeblocks
newlist = itertools.izip(reversed(xrange(len(codes))), reversed(codes)) # reverse list to hhhh1 does not match hhhh10 (Source: http://galvanist.com/post/53478841501/python-reverse-enumerate)
for i, c in newlist:
s = re.sub('hhhh' + str(i), c.encode('unicode-escape'), s) # Escaping here leads to backslashes being added in the code blocks.
return s
#################
# Split methods #
#################
def split_for_classification(self, outputdir='.'):
''' Takes a directory as input and writes twelve plain text files to this directory: a small test set, a large test set, and 10 files for the training set (trainpairs_[01-10].txt, testpairs_small.txt and testpairs_large.txt).
Each line in these sets contains two postids and a label (1 for duplicate, 0 for non-duplicate), separated by a space. Each of these pairs is a training or test instance.
The training pairs have been divided over ten different files, each with a similar class distribution. These can be used for ten-fold cross-validation.
To make the split all posts are ordered according to date. Next the set is cut into two at a certain date.
This date is chosen such that the test set will ideally contain at least 200 duplicate pairs, or if that iss not possible, as many as possible, with a minimum of 100, and the train set contains at least four times as many.
The test set contains pairs of posts with a date after the cutoff date. Posts are only combined with older posts, as would be the case in a real world setting. The training set contains pairs of posts with a date before the cutoff date. Again, posts are only combined with older posts.
A consequence of this approach is that we lose a number of duplicate pairs, namely the ones that are posted after the cutoff date, but their duplicate was posted before.
Both testpairs_large.txt and the trainpairs files will contain millions of pairs.
Testpairs_small.txt contains a subset of testpairs_large.txt. It is a smaller and more balanced set, which contains ten times more non-duplicate pairs than duplicate pairs.'''
if not self.cutoffdate:
self._find_cutoff_date()
if self.cutoffdate == 'nogood': # Should not happen with the supplied forums, only with the smaller ones I'm sometimes testing with.
#print "No candidate cutoff date could be found that satisfies our constraints."
#print "This means we cannot make splits for classification for this subforum."
return
sorted_all = self.get_ordered_list_of_posts()
# The above results in a list of tuples (postid, datetime object), ordered from newest to oldest post.
# Split the set
testposts = []
trainposts = []
for posttuple in sorted_all:
if posttuple[1] >= self.cutoffdate:
testposts.append(posttuple[0])
else:
trainposts.append(posttuple[0])
# Generate pairs and write them to files.
withdups = []
withoutdups = []
testfile = open(outputdir + '/' + self.cat + '_testpairs_large.txt', 'w')
for i,postid in enumerate(testposts):
dups = self.get_duplicates(postid)
combine_with = testposts[i+1:] # combine each post with older posts.
for otherpostid in combine_with:
if otherpostid in dups:
withdups.append((postid, otherpostid, '1'))
testfile.write(postid + ' ' + otherpostid + ' 1\n')
else:
withoutdups.append((postid, otherpostid, '0'))
testfile.write(postid + ' ' + otherpostid + ' 0\n')
testfile.close()
#print "Nr of duplicate pairs in the test sets:", len(withdups)
# Now we need to randomly pick non-duplicate pairs for the small test set.
# Here's an O(n) way to do it. This way, no searching and no trailing-element copying are made, but withoutdups is still getting smaller, to make sure we don't repeat picks.
# Source: http://code.activestate.com/recipes/59883-random-selection-of-elements-in-a-list-with-no-rep/ .
nrofnondups_forsmallset = len(withdups) * 10 # Take ten times the nr of duplicate pairs as non-duplicate pairs. The rest of the non-duplicate pairs will not be used in the small test set.
withoutdups_for_smallset = []
while nrofnondups_forsmallset > 0:
pos = randrange(len(withoutdups)) # randrange very conveniently excludes the last element of the list.
picked_nondup = withoutdups[pos]
withoutdups[pos] = withoutdups[-1] # Replace picked element with last one in the list
del withoutdups[-1] # Cheap removal of element
withoutdups_for_smallset.append(picked_nondup)
nrofnondups_forsmallset -= 1
testfile = open(outputdir + '/' + self.cat + '_testpairs_small.txt', 'w')
for tup in withdups:
testfile.write(tup[0] + ' ' + tup[1] + ' ' + tup[2] + '\n')
for tup in withoutdups_for_smallset:
testfile.write(tup[0] + ' ' + tup[1] + ' ' + tup[2] + '\n')
testfile.close()
totaltrainpairs = int(round(float(comb(len(trainposts), 2)),0))
print "total train pairs:", totaltrainpairs
trainfile1 = open(outputdir + '/' + self.cat + '_trainpairs_01.txt', 'w')
trainfile2 = open(outputdir + '/' + self.cat + '_trainpairs_02.txt', 'w')
trainfile3 = open(outputdir + '/' + self.cat + '_trainpairs_03.txt', 'w')
trainfile4 = open(outputdir + '/' + self.cat + '_trainpairs_04.txt', 'w')