O funcție de aplatizare a tweet-urilor
De obicei, lucrăm cu sute sau mii de tweet-uri. De aceea, are sens să definim o funcție care să aplatizeze un fișier JSON cu tweet-uri. Să numim această funcție flatten_tweets(). O vom folosi de mai multe ori în acest curs și o vom adapta ușor pe măsură ce lucrăm cu diferite tipuri de date.
json a fost deja importat pentru tine.
Acest exercițiu face parte din cursul
Analiza datelor din social media în Python
Instrucțiuni pentru exercițiu
- Stochează numele de utilizator în
user-screen_name. - Stochează textul tweet-ului extins în
extended_tweet-full_text. - Stochează numele de utilizator al autorului retweet-ului în
retweeted_status-user-screen_name. - Stochează textul retweet-ului în
retweeted_status-text.
Exercițiu interactiv practic
Încearcă acest exercițiu completând acest cod de exemplu.
def flatten_tweets(tweets_json):
""" Flattens out tweet dictionaries so relevant JSON
is in a top-level dictionary."""
tweets_list = []
# Iterate through each tweet
for tweet in tweets_json:
tweet_obj = json.loads(tweet)
# Store the user screen name in 'user-screen_name'
tweet_obj[____] = ____
# Check if this is a 140+ character tweet
if 'extended_tweet' in tweet_obj:
# Store the extended tweet text in 'extended_tweet-full_text'
tweet_obj[____] = ____
if 'retweeted_status' in tweet_obj:
# Store the retweet user screen name in 'retweeted_status-user-screen_name'
tweet_obj[____] = ____
# Store the retweet text in 'retweeted_status-text'
tweet_obj[____] = ____
tweets_list.append(tweet_obj)
return tweets_list