What is Twitter: A devil's tool that takes away the precious time of humankind
In order to reduce the time taken by Twitter as much as possible, let's make something that displays only highlight tweets at once!
・ Extract and display only the ones with the most favorites from the Twitter timeline ・ I wanted to know the trends of my friends, not news, so only the tweets of mutual followers are displayed.
We use something called the Twitter API.
API : Application Programming Interface
- A specification of the interface used by software components to interact with each other. Simply put, it is an interface that is set up so that it can be programmed more concisely in order to save the trouble of programming when programming an application. * Exhibitor: Wikipedia "Application Programming Interface"
I see, if you use the API, you can do various things without writing a lot of code. In particular, the API of the Web service is called the Web API, and it seems that it will be possible to acquire the data of the Web service. (This is also the Twitter API)
To use the Twitter API, you need to register your account on the developer site. https://dev.twitter.com/
You can find many ways to register by searching. http://qiita.com/hazigin/items/d9caf26c23c65bd89976 https://syncer.jp/twitter-api-matome http://webnaut.jp/develop/633.html
If you give a point ・ You need to register a phone number in your Twitter account ・ It is necessary to register the URL of the website to be created (local is OK for the time being) I feel like.
Once registration is complete ・ Consumer Key ・ Consumer Secret ・ Ass and Ken ・ Access Token Secret You can get 4 keys. You are now ready.
The language is Python. There seem to be several ways to access Twitter from Python, but this time I referred to this site.
top_fav_timeline.py
# -*- coding:utf-8 -*-
%matplotlib inline
from requests_oauthlib import OAuth1Session
import json
import datetime
import urllib, cStringIO
from PIL import Image
import matplotlib.pyplot as plt
#Get token
CK = '******************' # Consumer Key
CS = '******************' # Consumer Secret
AT = '******************' # Access Token
AS = '******************' # Accesss Token Secert
#You can set the upper and lower limits of the number of tweets read and the number of favos
def top_fav_timeline(count=100, minlim=2, maxlim=30):
"""Display those with mutual followers and a large number of favos
argument
count:
Number of timeline acquisitions (number of knot equals displayed)
!! Perhaps because of the upper limit of follow information acquisition, if you make it too large, it will not work!
minlim, maxlim:
Lower limit of number of favos
"""
#Get Key
twitter = OAuth1Session(CK,CS,AT,AS)
#Get timeline
url_timeline = "https://api.twitter.com/1.1/statuses/home_timeline.json"
#Parameter setting, here specify the number of timeline acquisitions
params_timeline = {'count':count}
#GET timeline with OAuth
req_timeline = twitter.get(url_timeline, params = params_timeline)
if req_timeline.status_code == 200:
#Since the response is in JSON format, parse it
timeline = json.loads(req_timeline.text)
#timeline user_get name
test = []
for i in range(len(timeline)):
test.append(timeline[i]["user"]["screen_name"])
test_s = ','.join(test)
params_friend = {'screen_name':test_s}
#Get user and follower status in timeline
url_friend = "https://api.twitter.com/1.1/friendships/lookup.json"
req_friend = twitter.get(url_friend, params = params_friend)
friend_test = json.loads(req_friend.text)
if req_friend.status_code == 200:
#Access each tweet data acquired by timeline
for tweet in timeline:
#Get follower status for tweeted users
for i in range(len(friend_test)):
if friend_test[i]['screen_name'] == tweet["user"]["screen_name"]:
test_num = i
#If the tweeting user is a mutual follower, it will be displayed in the timeline
if u'followed_by' in friend_test[test_num]['connections']:
# favorite_Display count above threshold
if tweet["favorite_count"] >= minlim and tweet["favorite_count"] <= maxlim:
#Image display
file = cStringIO.StringIO(urllib.urlopen(tweet["user"]["profile_image_url_https"]).read())
img = Image.open(file)
#plt options various settings
plt.figure(figsize=(0.5,0.5)) #size
plt.axis('off') #Hide memory line
plt.imshow(img)
plt.show()
#Convert tweet time to datetime type and convert to Japan time
dst = datetime.datetime.strptime(tweet["created_at"],'%a %b %d %H:%M:%S +0000 %Y') + datetime.timedelta(hours=9)
#Display in timeline
print dst
print tweet["user"]["name"] + " / @" + tweet["user"]["screen_name"]
print tweet["text"]
print '★:' + str(tweet["favorite_count"])
print '-------'
else:
#If the timeline could not be obtained
print ("Error: %d" % req.status_code)
It's done. It's full of for and if and it feels bad. Since I wrote it in juyter notebook,% matplotlib inline is at the beginning.
When you run ·profile image ・ Tweet time ・ Id and display name ・ Tweet text ・ Number of favos Is printed. It was troublesome to fetch the screen_name from the timeline in advance so as not to make multiple requests, and to access the image URL to display the profile image and pull the image directly from online and display it on jupyter. ..
This time, we selected and displayed mutual follow tweets, but if you change the conditions a little, you should be able to display only mutual follow "not" tweets. It may be useful for searching for news that is often favored.
You can get the information of the tweet on the timeline with GET statuses / home_timeline, but I think that you can do various things because you can get various information such as the tweet body, profile image, tweet time and the user who tweeted. ..
Let's Enjoy Twitter!
Twitter API TIPS https://dev.twitter.com/rest/public
Access Twitter API with Python http://qiita.com/yubais/items/dd143fe608ccad8e9f85
A lot of OAuth keys appear, but I tried to summarize each role http://d.hatena.ne.jp/mabots/20100615/1276583402
To convert a string date to datetime in Python. http://loumo.jp/wp/archive/20110408215311/
Recommended Posts