On Twitter, if a tweet contains a specific keyword, A script to save to CSV.
twitcsvfield.py
#!/user/bin/env python
# -*- coding: utf-8 -*-
from requests_oauthlib import OAuth1Session
import csv
import json
import sys, codecs
C_KEY = "*************************"
C_SECRET = "*************************"
A_KEY = "*************************"
A_SECRET = "*************************"
def Home_timeline(field):
url = "https://api.twitter.com/1.1/statuses/home_timeline.json"
params = {
"lang": "ja",
"count": "100"
}
tw = OAuth1Session(C_KEY,C_SECRET,A_KEY,A_SECRET)
req = tw.get(url, params = params)
tweets = json.loads(req.text)
f = open("tweetsearch.csv" , "ab")
writer = csv.writer(f)
writer.writerow(["Datatime", "User", "Name", "Text", "Place"])
for tweet in tweets:
created_at = (tweet["created_at"])
User = (tweet["user"]["screen_name"].encode("utf-8"))
Name = (tweet["user"]["name"].encode("utf-8"))
Text = (tweet["text"].encode("utf-8"))
Place = (tweet["place"])
if (tweet["text"]) == field:
writer.writerow([created_at, User, Name, Text, Place])
f.close()
else:
pass
return Home_timeline
def Limit_Status():
url = "https://api.twitter.com/1.1/application/rate_limit_status.json"
params = {}
tw = OAuth1Session(C_KEY,C_SECRET,A_KEY,A_SECRET)
req = tw.get(url, params = params)
if req.status_code == 200:
limit = req.headers["x-rate-limit-remaining"]
print ("API remain: " + limit)
return Limit_Status
Home_timeline(u"test")
Limit_Status()
In this sample, if the string "test" exists in home_timeline, save it. As usual, if there is no CSV file, it will be created, if there is, it will be overwritten, so Note that CSV headers will be duplicated if acquired continuously.
I feel like I can play with various modifications from here.
Recommended Posts