[PYTHON] Save tweets containing specific keywords in CSV on Twitter

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

Save tweets containing specific keywords in CSV on Twitter
A script that transfers tweets containing specific Twitter keywords to Slack in real time
A Python program that collects tweets containing specific keywords daily and saves them in csv
Save the search results on Twitter to CSV.
Save Twitter's tweets with Geo in CSV and plot them on Google Map.
Continue to retrieve tweets containing specific keywords using the Streaming API in Python
Get only image tweets on twitter
Save a specific variable in tensorflow.session
Get tweets containing keywords using Python Tweepy
Get images from specific users on Twitter
Extract lines containing a specific "string" in Pandas
Get a row containing a specific element in np.where