Python 100 project #7: Trending Wordcloud – added country selection

This is more like a small modification on my previous project.

I have noticed I can select the country to look what kind of words are hot in the selected country.

I made a dictionary so that the user can pass the country name and it returns the respective trends.

 

Output Example: Trending words in Japan

 

Here is the code:

COUNTRYDICT = {'Argentina': 'p30', 'Australia': 'p8', 'Austria': 'p44', 'Belgium': 'p41',
               'Brazil': 'p18', 'Canada': 'p13', 'Chile': 'p38', 'Colombia': 'p32',
               'Czech Republic': 'p43', 'Egypt': 'p29', 'Finland': 'p50', 'France': 'p16',
               'Germany': 'p15', 'Greece': 'p48', 'Hong Kong': 'p10', 'Hungary': 'p45',
               'India': 'p3', 'Indonesia': 'p19', 'Israel': 'p6', 'Italy': 'p27',
               'Japan': 'p4', 'Kenya': 'p37', 'Malaysia': 'p34', 'Mexico': 'p21',
               'Netherlands': 'p17', 'New Zealand': 'p53', 'Nigeria': 'p52', 'Norway': 'p51',
               'Philippines': 'p25', 'Poland': 'p31', 'Romania': 'p39', 'Russia': 'p14',
               'Saudi Arabia': 'p36', 'Singapore': 'p5', 'South Africa': 'p40', 'South Korea': 'p23',
               'Spain': 'p26', 'Sweden': 'p42', 'Switzerland': 'p46', 'Taiwan': 'p12',
               'Thailand': 'p33', 'Turkey': 'p24', 'Ukraine': 'p35', 'United Kingdom': 'p9',
               'United States': 'p1', 'Vietnam': 'p28'}


def get_latest_trends(pn='p1'):
    from pytrends.request import TrendReq

    pytrend = TrendReq()

    trending_searches_df = pytrend.trending_searches(pn=pn)

    trending_dict = {}

    for id, row in trending_searches_df.iterrows():
        trending_dict[row.title] = row.trafficBucketLowerBound

    return trending_dict


def generate_wordcloud(mask_image, word_dict):
    from wordcloud import WordCloud
    import numpy as np
    from PIL import Image

    # macOS needs to specify Fonts
    fpath = "/System/Library/Fonts/ヒラギノ角ゴシック W8.ttc"

    mask = np.array(Image.open(mask_image))

    wordcloud = WordCloud(mask=mask)
    wordcloud.generate_from_frequencies(frequencies=word_dict)

    image = wordcloud.to_file('trending.png')

word_dict = get_latest_trends(pn=COUNTRYDICT['Japan'])
generate_wordcloud('data_source/0000.png',word_dict)