Skip to content

Commit

Permalink
test 16
Browse files Browse the repository at this point in the history
  • Loading branch information
MartinMousa committed Jun 18, 2024
1 parent 89688b3 commit 5c7527e
Showing 1 changed file with 47 additions and 0 deletions.
47 changes: 47 additions & 0 deletions 0x16-api_advanced/100-count.py
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"))

0 comments on commit 5c7527e

Please sign in to comment.