forked from luifap/holberton-system_engineering-devops-1
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path100-count.py
executable file
·47 lines (38 loc) · 1.57 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
"""Module for task 3"""
def count_words(subreddit, word_list, word_count={}, after=None):
"""Queries the Reddit API and returns the count of words in
word_list in the titles of all the hot posts
of the subreddit"""
import requests
sub_info = requests.get("https://www.reddit.com/r/{}/hot.json"
.format(subreddit),
params={"after": after},
headers={"User-Agent": "My-User-Agent"},
allow_redirects=False)
if sub_info.status_code != 200:
return None
info = sub_info.json()
hot_l = [child.get("data").get("title")
for child in info
.get("data")
.get("children")]
if not hot_l:
return None
word_list = list(dict.fromkeys(word_list))
if word_count == {}:
word_count = {word: 0 for word in word_list}
for title in hot_l:
split_words = title.split(' ')
for word in word_list:
for s_word in split_words:
if s_word.lower() == word.lower():
word_count[word] += 1
if not info.get("data").get("after"):
sorted_counts = sorted(word_count.items(), key=lambda kv: kv[0])
sorted_counts = sorted(word_count.items(),
key=lambda kv: kv[1], reverse=True)
[print('{}: {}'.format(k, v)) for k, v in sorted_counts if v != 0]
else:
return count_words(subreddit, word_list, word_count,
info.get("data").get("after"))