My workbooks
β€Œ
β€Œ
β€Œ
β€Œ
β€Œ
β€Œ
β€Œ
β€Œ
β€Œ
β€Œ
β€Œ
β€Œ
β€Œ
β€Œ
Sign up
Beta
Spinner

1. Local and global thought patterns

While we might not be Twitter fans, we have to admit that it has a huge influence on the world (who doesn't know about Trump's tweets). Twitter data is not only gold in terms of insights, but Twitter-storms are available for analysis in near real-time. This means we can learn about the big waves of thoughts and moods around the world as they arise.

As any place filled with riches, Twitter has security guards blocking us from laying our hands on the data right away ⛔️ Some authentication steps (really straightforward) are needed to call their APIs for data collection. Since our goal today is learning to extract insights from data, we have already gotten a green-pass from security βœ… Our data is ready for usage in the datasets folder β€” we can concentrate on the fun part! πŸ•΅οΈβ€β™€οΈπŸŒŽ



Twitter provides both global and local trends. Let's load and inspect data for topics that were hot worldwide (WW) and in the United States (US) at the moment of query β€” snapshot of JSON response from the call to Twitter's GET trends/place API.

Note: Here is the documentation for this call, and here a full overview on Twitter's APIs.

# Loading json module
import pandas as pd
import json

# Loading WW_trends and US_trends data
WW_trends = json.loads(open('datasets/WWTrends.json').read())
US_trends = json.loads(open('datasets/USTrends.json').read())

# Inspecting data by printing out WW_trends and US_trends variables
print(WW_trends)
print(US_trends)

2. Prettifying the output

Our data was hard to read! Luckily, we can resort to the json.dumps() method to have it formatted as a pretty JSON string.

# Pretty-printing the results. First WW and then US trends. 

print("WW trends:")
print (json.dumps(WW_trends, indent=1))

print("\n", "US trends:")
print (json.dumps(US_trends, indent=1))

3. Finding common trends

πŸ•΅οΈβ€β™€οΈ From the pretty-printed results (output of the previous task), we can observe that:

  • We have an array of trend objects having: the name of the trending topic, the query parameter that can be used to search for the topic on Twitter-Search, the search URL and the volume of tweets for the last 24 hours, if available. (The trends get updated every 5 mins.)

  • At query time #BeratKandili, #GoodFriday and #WeLoveTheEarth were trending WW.

  • "tweet_volume" tell us that #WeLoveTheEarth was the most popular among the three.

  • Results are not sorted by "tweet_volume".

  • There are some trends which are unique to the US.


It’s easy to skim through the two sets of trends and spot common trends, but let's not do "manual" work. We can use Python’s set data structure to find common trends β€” we can iterate through the two trends objects, cast the lists of names to sets, and call the intersection method to get the common names between the two sets.

# Extracting all the WW trend names from WW_trends
world_trends = set([trend['name']                    
                    for trend in WW_trends[0]['trends']])

# Extracting all the US trend names from US_trends
us_trends = set([trend['name'] 
                     for trend in US_trends[0]['trends']]) 

# Let's get the intersection of the two sets of trends
common_trends = world_trends.intersection(us_trends)

# Inspecting the data
print(world_trends, "\n")
print(us_trends, "\n")
print (len(common_trends), "common trends:", common_trends)

4. Exploring the hot trend

πŸ•΅οΈβ€β™€οΈ From the intersection (last output) we can see that, out of the two sets of trends (each of size 50), we have 11 overlapping topics. In particular, there is one common trend that sounds very interesting: #WeLoveTheEarth β€” so good to see that Twitteratis are unanimously talking about loving Mother Earth! πŸ’š

Note: We could have had no overlap or a much higher overlap; when we did the query for getting the trends, people in the US could have been on fire obout topics only relevant to them.

Image Source:Official Music Video Cover: https://welovetheearth.org/video/

We have found a hot-trend, #WeLoveTheEarth. Now let's see what story it is screaming to tell us!
If we query Twitter's search API with this hashtag as query parameter, we get back actual tweets related to it. We have the response from the search API stored in the datasets folder as 'WeLoveTheEarth.json'. So let's load this dataset and do a deep dive in this trend.

# Loading the data
with open("datasets/WeLoveTheEarth.json", "r") as file:
    f = file.read()
    
tweets = json.loads(f)

# Inspecting some tweets
tweets[0]

5. Digging deeper

πŸ•΅οΈβ€β™€οΈ Printing the first two tweet items makes us realize that there’s a lot more to a tweet than what we normally think of as a tweet β€” there is a lot more than just a short text!


But hey, let's not get overwhemled by all the information in a tweet object! Let's focus on a few interesting fields and see if we can find any hidden insights there.

# Extracting the text of all the tweets from the tweet object
texts = [tweet['text'] 
                 for tweet in tweets ]

# Extracting screen names of users tweeting about #WeLoveTheEarth
names = [user_mention['screen_name'] 
                 for tweet in tweets
                     for user_mention in tweet['entities']['user_mentions']]

# Extracting all the hashtags being used when talking about this topic
hashtags = [hashtag['text'] 
             for tweet in tweets
                 for hashtag in tweet['entities']['hashtags']]

# Inspecting the first 10 results
print (json.dumps(texts[0:10], indent=1),"\n")
print (json.dumps(names[0:10], indent=1),"\n")
print (json.dumps(hashtags[0:10], indent=1),"\n")

6. Frequency analysis

πŸ•΅οΈβ€β™€οΈ Just from the first few results of the last extraction, we can deduce that:

  • We are talking about a song about loving the Earth.
  • A lot of big artists are the forces behind this Twitter wave, especially Lil Dicky.
  • Ed Sheeran was some cute koala in the song β€” "EdSheeranTheKoala" hashtag! 🐨

Observing the first 10 items of the interesting fields gave us a sense of the data. We can now take a closer look by doing a simple, but very useful, exercise β€” computing frequency distributions. Starting simple with frequencies is generally a good approach; it helps in getting ideas about how to proceed further.

# Importing modules
from collections import Counter

# Counting occcurrences/ getting frequency dist of all names and hashtags
for item in [names, hashtags]:
    c = Counter(item) 
    # Inspecting the 10 most common items in c
    print (c.most_common(10), "\n")

7. Activity around the trend

πŸ•΅οΈβ€β™€οΈ Based on the last frequency distributions we can further build-up on our deductions:

  • We can more safely say that this was a music video about Earth (hashtag 'EarthMusicVideo') by Lil Dicky.
  • DiCaprio is not a music artist, but he was involved as well (Leo is an environmentalist so not a surprise to see his name pop up here).
  • We can also say that the video was released on a Friday; very likely on April 19th.

We have been able to extract so many insights. Quite powerful, isn't it?!


Let's further analyze the data to find patterns in the activity around the tweets β€” did all retweets occur around a particular tweet?

If a tweet has been retweeted, the 'retweeted_status' field gives many interesting details about the original tweet itself and its author.

We can measure a tweet's popularity by analyzing the retweetcount and favoritecount fields. But let's also extract the number of followers of the tweeter β€” we have a lot of celebs in the picture, so can we tell if their advocating for #WeLoveTheEarth influenced a significant proportion of their followers?


Note: The retweet_count gives us the total number of times the original tweet was retweeted. It should be the same in both the original tweet and all the next retweets. Tinkering around with some sample tweets and the official documentaiton are the way to get your head around the mnay fields.

# Extracting useful information from retweets
retweets = [
             (tweet['retweet_count'], 
              tweet['retweeted_status']['favorite_count'],
              tweet['retweeted_status']['user']['followers_count'],
              tweet['retweeted_status']['user']['screen_name'],
              tweet['text']) 
            
            for tweet in tweets 
                if 'retweeted_status' in tweet
           ]
Hidden output

8. A table that speaks a 1000 words

Let's manipulate the data further and visualize it in a better and richer way β€” "looks matter!"

β€Œ
β€Œ
β€Œ
  • AI Chat
  • Code