Home > Enterprise >  Changing outputs with Twitter API
Changing outputs with Twitter API

Time:08-29

I am trying to make a program that prints how many times a specific keyword has been tweeted about per hour with the Twitter API. I have already fixed the code where it will output the data.

from operator import truediv
from urllib import response
import tweepy
import config
import datetime

client = tweepy.Client(bearer_token=config.BEARER_TOKEN)

query = 'Python'

counts = client.get_recent_tweets_count(query=query,
                                        granularity='hour',
                                        start_time='2022-08-27T13:00:00 05:00',
                                        end_time='2022-08-27T14:00:00 05:00')

for count in counts.data:
    print(count)

This code will output the starting time of the search as well as the stopping time and the amount of tweets about said keyword during the hour. However, I am trying to take the actual tweet count number and save it to a file. How can I cut my output down to just the actual tweet number? Here is a sample output of my code.

{'end': '2022-08-27T09:00:00.000Z', 'start': '2022-08-27T08:00:00.000Z', 
'tweet_count': 2067}

CodePudding user response:

count is a json object, you just need to parse it:

import json
Obj = json.loads(count)
# the result is a Python dictionary
print(Obj['tweet_count'])

CodePudding user response:

Your output seems to be a dictionary, so you can access an item by it's name:

tweets = counts.data['tweet_count']
print(tweets)
  • Related