简体   繁体   中英

How to extract only tweets from this json file?

I have mined some tweets from Barack Obama and now i want to extract the tweets only.

Here is the code with which i loaded the json file into python:

import json

# load Tweets from Bill Gates
with open(f'output/'"BarackObama.json", 'r') as json_file:
    data = json.load(json_file)
print(data)

This is the outcome:

[{'Total Tweets Found': 192, 'Name': 'Barack Obama', 'Bio': 'Dad, husband, President, citizen.', 'followers_count': 130536244, 'friends_count': 587154, 'Tweets found from 2010-01-01 to 2022-01-06:': 191}, {'sr.no': 1, 'ID': 1479090410211393543, 'date_time_posted': '2022-01-06 14:00:08+00:00', 'tweet': 'One year ago, a violent attack on our Capitol made it clear just how fragile the American experiment in democracy really is. Here’s my statement on what the anniversary means, and what we need to do today.}, {'sr.no': 2, 'ID': 1477301228405198854, 'date_time_posted': '2022-01-01 15:30:34+00:00', 'tweet': 'I’m hopeful about 2022. This year will undoubtedly have its challenges, just like 2021 did. But we’ve made it this far—and I still believe we can build a brighter future together. Happy New Year!'}, 

and so on...

I only want to use the tweets.

We just have to iterate over the list and select the tweet:

import json

with open(f'output/'"BarackObama.json", 'r') as json_file:
    data = json.load(json_file)

tweets = []
for i, _ in enumerate(data):
    try:
        tweets.append(data[i]['tweet'])
    except KeyError:
        pass

print(tweets)

I think we can simply get the results out of this with a simple loop considering the output is a list of dictionaries.

tweets = []
key = 'tweet'
for post in data:
    if key in post:
        tweet = post['tweet']
        tweets.append(tweet)

print(tweets)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM