-
Notifications
You must be signed in to change notification settings - Fork 1
/
100-count.py
38 lines (35 loc) · 1.34 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
#!/usr/bin/python3
"""Contains the count_words function"""
import requests
def count_words(subreddit, word_list, found_list=[], after=None):
"""
Prints counts of given words found in hot posts of a given subreddit
"""
user_agent = {'User-agent': 'test45'}
posts = requests.get('http://www.reddit.com/r/{}/hot.json?after={}'
.format(subreddit, after), headers=user_agent)
if after is None:
word_list = [word.lower() for word in word_list]
if posts.status_code == 200:
posts = posts.json()['data']
aft = posts['after']
posts = posts['children']
for post in posts:
title = post['data']['title'].lower()
for word in title.split(' '):
if word in word_list:
found_list.append(word)
if aft is not None:
count_words(subreddit, word_list, found_list, aft)
else:
result = {}
for word in found_list:
if word.lower() in result.keys():
result[word.lower()] += 1
else:
result[word.lower()] = 1
for key, value in sorted(result.items(), key=lambda item: item[1],
reverse=True):
print('{}: {}'.format(key, value))
else:
return