Python Twitter Api RT 分ける
この記事には誤りがあります.この方法でもできますが….
上記記事でほぼ解決していたのですが,そのユーザが投稿したわけではない(そのユーザがRTした)ツイートがまざるのがいやだったので,少し調べました.
どうやら各ツイートのretweeted_statuの存在の有無を調べるらしいのですが,
tweet["retweeted_statu"] == {} tweet["retweeted_statu"] is None
両方ダメだったので,少し悩みました.いや言われればそのまんまなんですけどね.
というわけで上記記事に完全にマウントして,streamからツイートを取得しましょう.ついでにハッシュタグとURLも消しました.すっきり!
import requests import json from requests_oauthlib import OAuth1 import re consumer_key = "bokuha" consumer_secret = "pikachu" access_token = "ga" access_secret = "daisuke!" url = "https://stream.twitter.com/1.1/statuses/filter.json" auth = OAuth1(consumer_key, consumer_secret, access_token, access_secret) r = requests.post(url, auth=auth, stream=True, data={"track":"pokemon"}) if r.status_code == 200: print ("connect succeed!") else: print ("Error: %d" % r.status_code) for line in r.iter_lines(): stream = line.decode("utf-8") try: find=json.loads(stream) #読み込み print("------------------------------") try: #ここでRTが判断している.関数化しようかとも思ったが,そこまで複雑じゃないので isRtweeted = not find["retweeted_status"] == {} except KeyError: isRtweeted = False if isRtweeted: print(find["user"]["name"] + "がRTしました") else: t1 = re.sub(r"(\s*https?|ftp)(:\/\/[-_\.!~*\'()a-zA-Z0-9;\/?:\@&=\+\$,%#]+)", "" ,find["text"]) #URLを削除 t2 = re.sub(r"(\s*#\S+\s*)", "", t1) #ハッシュタグを削除 print(find["user"]["name"], t2) print(find["entities"]["hashtags"]) except json.decoder.JSONDecodeError: pass except: print ("unknown error!") pass #たまによくわからないエラーが出るらしいです.