-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
89688b3
commit 5c7527e
Showing
1 changed file
with
47 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,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/%7B%7D/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")) |