-
Notifications
You must be signed in to change notification settings - Fork 0
/
100-count.py
50 lines (38 loc) · 1.59 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
48
49
50
#!/usr/bin/python3
""" Module for a function that queries the Reddit API recursively."""
import requests
def count_words(subreddit, word_list, after='', word_dict={}):
""" A function that queries the Reddit API parses the title of
all hot articles, and prints a sorted count of given keywords
(case-insensitive, delimited by spaces.
Javascript should count as javascript, but java should not).
If no posts match or the subreddit is invalid, it prints nothing.
"""
if not word_dict:
for word in word_list:
if word.lower() not in word_dict:
word_dict[word.lower()] = 0
if after is None:
wordict = sorted(word_dict.items(), key=lambda x: (-x[1], x[0]))
for word in wordict:
if word[1]:
print('{}: {}'.format(word[0], word[1]))
return None
url = 'https://www.reddit.com/r/{}/hot/.json'.format(subreddit)
header = {'user-agent': 'redquery'}
parameters = {'limit': 100, 'after': after}
response = requests.get(url, headers=header, params=parameters,
allow_redirects=False)
if response.status_code != 200:
return None
try:
hot = response.json()['data']['children']
aft = response.json()['data']['after']
for post in hot:
title = post['data']['title']
lower = [word.lower() for word in title.split(' ')]
for word in word_dict.keys():
word_dict[word] += lower.count(word)
except Exception:
return None
count_words(subreddit, word_list, aft, word_dict)