-
Notifications
You must be signed in to change notification settings - Fork 0
/
100-count.py
executable file
·47 lines (38 loc) · 1.39 KB
/
100-count.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
#!/usr/bin/python3
"""
Function to count words in all hot posts of a given Reddit subreddit.
"""
import requests
def count_words(subreddit, word_list, after=None, counts={}):
"""
Recursive function that queries the Reddit API, parses the title of all
hot articles, and prints a sorted count of given keywords
"""
if not word_list or word_list == [] or not subreddit:
return
url = f"https://www.reddit.com/r/{subreddit}/hot.json"
headers = {"User-Agent": "Mozilla/5.0"}
params = {"limit": 100}
if after:
params["after"] = after
response = requests.get(url,
headers=headers,
params=params,
allow_redirects=False)
if response.status_code != 200:
return
data = response.json()
children = data["data"]["children"]
for post in children:
title = post["data"]["title"].lower()
for word in word_list:
if word.lower() in title:
counts[word] = counts.get(word, 0) + title.count(word.lower())
after = data["data"]["after"]
if after:
count_words(subreddit, word_list, after, counts)
else:
sorted_counts = sorted(counts.items(),
key=lambda x: (-x[1], x[0].lower()))
for word, count in sorted_counts:
print(f"{word.lower()}: {count}")