Skip to content

Instantly share code, notes, and snippets.

@bobturneruk
Created September 4, 2019 13:26
Show Gist options
  • Save bobturneruk/596809e0f4569e30e6e8a6f7198f1ad0 to your computer and use it in GitHub Desktop.
Save bobturneruk/596809e0f4569e30e6e8a6f7198f1ad0 to your computer and use it in GitHub Desktop.
# Required libraries
from twython import Twython
import json
import pandas as pd
# Access Twitter API using twython
APP_KEY = '' # Use your API KEY
APP_SECRET = '' # Use your secret
twitter = Twython(APP_KEY, APP_SECRET, oauth_version=2)
ACCESS_TOKEN = twitter.obtain_access_token()
twitter = Twython(APP_KEY, access_token=ACCESS_TOKEN)
# Execute a search for "GMO" in English returning 100 records
twit_py_json=twitter.search(q='GMO',count=100,lang='en') #found I needed to set count or I get an incomplete .json string
# Save the .json file
jsonfile=open('jsonfile.json','w')
json.dump(twit_py_json,jsonfile)
jsonfile.close()
# Make a pandas dataframe
data_i_want=[] #empty list
for status in twit_py_json['statuses']: #loop through all tweets AKA statuses
data_i_want.append({'id':status['id'],'text':status['text']}) #take the "id" and "text" fields, and add to the empty list
data_i_want_df=pd.DataFrame(data_i_want) #turn the list into a dataframe
# Save the data to Excel (note that the data type of columns may not be respected)
data_i_want_df.to_excel('tweets.xlsx',sheet_name='GMO')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment