-
Notifications
You must be signed in to change notification settings - Fork 0
/
reddit.py
75 lines (59 loc) · 1.96 KB
/
reddit.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
from argparse import ArgumentParser
from datetime import datetime
from typing import Callable, Dict
import orjson as json
import pandas as pd
from pandas import DataFrame
from tqdm import tqdm
KEY_MAPPING: Dict[str, Callable] = {
"id": str,
"created_utc": lambda x: datetime.utcfromtimestamp(int(x)),
"author": str,
"num_comments": int,
"score": int,
"selftext": str,
"title": str,
"subreddit": str,
"subreddit_id": str,
"url": str,
}
def load_and_filter(line: str, threshold: int):
parsed = json.loads(line)
result = {}
for (key, mapping) in KEY_MAPPING.items():
try:
result[key] = mapping(parsed[key])
except KeyError:
return None
except TypeError:
print(key, parsed[key], mapping, type(parsed[key]))
raise SystemError
if result["score"] < threshold:
return None
return result
if __name__ == "__main__":
parser = ArgumentParser()
parser.add_argument("-y", "--year", type=int, required=True)
parser.add_argument("-m", "--month", type=int, required=True)
parser.add_argument("-t", "--threshold", type=int, required=True)
flags = vars(parser.parse_args())
threshold = flags["threshold"]
input_file = f"RS_{flags['year']:4d}-{flags['month']:02d}.csv"
output_file = f"out-{input_file}"
with open(input_file, "r") as f:
data = []
for line in tqdm(f):
processed = load_and_filter(line, threshold=threshold)
if processed is not None:
data.append(processed)
df = DataFrame.from_records(data)
del data
df = df[pd.to_numeric(df.score, errors="coerce").notnull()]
df.score = df.score.astype(int)
df = df[df.score >= threshold]
df = df[df.selftext != ""]
df = df[df.selftext != "nan"]
df = df[df.selftext != "[deleted]"]
df = df[df.selftext != "[removed]"]
print("Count: {}".format(len(df.index)))
df.to_csv(output_file)