Uma função para achatar tweets
Geralmente, estamos interessados em centenas ou milhares de tweets. Para isso, faz sentido definir uma função para achatar um arquivo JSON cheio de tweets. Vamos chamar essa função de flatten_tweets(). Vamos usá-la várias vezes neste curso e fazer pequenas alterações conforme lidamos com diferentes tipos de dados.
json já foi carregado para você.
Este exercício faz parte do curso
Analisando dados de mídias sociais em Python
Instruções do exercício
- Armazene o nome de usuário (screen name) em
user-screen_name. - Armazene o texto do tweet estendido em
extended_tweet-full_text. - Armazene o nome de usuário do retweet em
retweeted_status-user-screen_name. - Armazene o texto do retweet em
retweeted_status-text.
Exercício interativo prático
Experimente este exercício completando este código de exemplo.
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