forked from Watchful1/Sketchpad
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathoverlapCounter.py
163 lines (138 loc) · 5.71 KB
/
overlapCounter.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
import requests
from collections import defaultdict
from datetime import datetime, timedelta
import time
import os
import json
subreddits = ['Scottishpeopletwitter','Britishproblems','Purplepilldebate','Sinkpissers','Boneappletea','Whereareallthegoodmen']
ignored_users = ['[deleted]', 'automoderator']
lookback_days = 180
min_comments_per_sub = 1
file_name = "users.txt"
url = "https://api.pushshift.io/reddit/comment/search?&limit=1000&sort=desc&subreddit={}&before="
startTime = datetime.utcnow()
startEpoch = int(startTime.timestamp())
endTime = startTime - timedelta(days=lookback_days)
endEpoch = int(endTime.timestamp())
totalSeconds = startEpoch - endEpoch
if not os.path.exists("overlap_subreddits"):
os.makedirs("overlap_subreddits")
def loadSubredditCommenters(subreddit):
for filename in os.listdir("overlap_subreddits"):
if filename.endswith(".txt") and filename.startswith(subreddit):
count_comments = 0
with open(os.path.join("overlap_subreddits", filename), 'r') as inputFile:
commenters = defaultdict(int)
for line in inputFile:
items = line.split(" ")
if len(items) != 2:
print(f"Error loading line for {subreddit}: {line}")
continue
user_comments = int(items[1])
commenters[items[0]] = user_comments
count_comments += user_comments
dateString = filename.split("_")[-1][:-4]
print(f"Loaded {len(commenters)} commenters for subreddit r/{subreddit} through {dateString}")
dateThrough = datetime.strptime(dateString, '%Y-%m-%d')
return commenters, int(dateThrough.timestamp()), count_comments
return None, None, 0
def saveSubredditCommenters(subreddit, commenters, dateThrough):
if dateThrough is None:
return
#print(f"Saving {len(commenters)} commenters for subreddit r/{subreddit} through {dateThrough.strftime('%Y-%m-%d')}")
for filename in os.listdir("overlap_subreddits"):
if filename.endswith(".txt") and filename.startswith(subreddit):
os.remove(os.path.join("overlap_subreddits", filename))
with open(os.path.join("overlap_subreddits", f"{subreddit}_{dateThrough.strftime('%Y-%m-%d')}.txt"), 'w') as outputFile:
for commenter, countComments in commenters.items():
outputFile.write(commenter)
outputFile.write(" ")
outputFile.write(str(countComments))
outputFile.write("\n")
def countCommenters(subreddit):
commenters, previousEpoch, count = loadSubredditCommenters(subreddit)
if commenters is None:
commenters = defaultdict(int)
previousEpoch = startEpoch
print(f"Counting commenters in: {subreddit}")
breakOut = False
currentDate = None
while True:
newUrl = url.format(subreddit)+str(previousEpoch)
try:
response = requests.get(newUrl, headers={'User-Agent': "Overlap counter by /u/Watchful1"})
except requests.exceptions.ReadTimeout:
print(f"Pushshift timeout, this usually means pushshift is down. Waiting 5 seconds and trying again: {newUrl}")
time.sleep(5)
continue
try:
objects = response.json()['data']
except json.decoder.JSONDecodeError:
print(f"Decoding error, this usually means pushshift is down. Waiting 5 seconds and trying again: {newUrl}")
time.sleep(5)
continue
time.sleep(1) # pushshift is ratelimited. If we go too fast we'll get errors
if len(objects) == 0:
break
for object in objects:
previousEpoch = object['created_utc'] - 1
if object['author'] not in ignored_users:
commenters[object['author']] += 1
count += 1
if count % 1000 == 0:
currentDatetime = datetime.fromtimestamp(previousEpoch)
print("r/{0} comments: {1}, {2}, {3:.2f}%".format(
subreddit,
count,
currentDatetime.strftime("%Y-%m-%d"),
((startEpoch - previousEpoch) / totalSeconds) * 100))
if currentDatetime.date() != currentDate:
saveSubredditCommenters(subreddit, commenters, currentDatetime)
currentDate = currentDatetime.date()
if previousEpoch < endEpoch:
breakOut = True
currentDate = datetime.fromtimestamp(previousEpoch).date()
break
if breakOut:
break
saveSubredditCommenters(subreddit, commenters, currentDate)
print(f"Comments: {count}, commenters: {len(commenters)}")
return commenters
commenterSubreddits = defaultdict(int)
for subreddit in subreddits:
commenters = countCommenters(subreddit)
for commenter in commenters:
if commenters[commenter] >= min_comments_per_sub:
commenterSubreddits[commenter] += 1
sharedCommenters = defaultdict(list)
for commenter, countSubreddits in commenterSubreddits.items():
if countSubreddits >= len(subreddits) - 2:
sharedCommenters[countSubreddits].append(commenter)
commentersAll = len(sharedCommenters[len(subreddits)])
commentersMinusOne = len(sharedCommenters[len(subreddits) - 1])
commentersMinusTwo = len(sharedCommenters[len(subreddits) - 2])
print(f"{commentersAll} commenters in all subreddits, {commentersMinusOne} in all but one, {commentersMinusTwo} in all but 2")
with open(file_name, 'w') as txt:
if commentersAll == 0:
txt.write(f"No commenters in all subreddits\n")
else:
txt.write(f"{commentersAll} commenters in all subreddits\n")
for user in sorted(sharedCommenters[len(subreddits)], key=str.lower):
txt.write(f"{user}\n")
txt.write("\n")
if commentersAll < 10:
if commentersMinusOne == 0:
txt.write(f"No commenters in all but one subreddits\n")
else:
txt.write(f"{commentersMinusOne} commenters in all but one subreddits\n")
for user in sorted(sharedCommenters[len(subreddits) - 1], key=str.lower):
txt.write(f"{user}\n")
txt.write("\n")
if commentersMinusOne < 10:
if commentersMinusTwo == 0:
txt.write(f"No commenters in all but two subreddits\n")
else:
txt.write(f"{commentersMinusTwo} commenters in all but two subreddits\n")
for user in sorted(sharedCommenters[len(subreddits) - 2], key=str.lower):
txt.write(f"{user}\n")
txt.write("\n")