前提
twitterapiを利用してtweetデータを取得することはできています。
また、取得したデータから特定のキーワードを入力してキーワードを含むツイート数は出力できています
実現したいこと
取得したtweetデータ(jsonファイル)から特定のキーワードを含むツイートを取得したい。
tweetデータの取得プログラム
python
1import json 2import sys 3import datetime 4from time import sleep 5#Variables that contains the user credentials to access Twitter API 6access_token = '***********' 7access_token_secret = '*********' 8consumer_key = "************" 9consumer_secret = "*************" 10#This is a basic listener that just prints received tweets to stdout. 11import tweepy 12class IDPrinter(tweepy.Stream): 13 def on_status(self, status): 14 print(status.id) 15class CustomStreamListener(tweepy.Stream): 16 def on_data(self,data): 17 #print("=>",data) 18 tweet=json.loads(data) 19 #tweetにtextキーがあるかないか 20 if("text" in tweet): 21 try: 22 23 if tweet['lang']=='ja' or tweet["user"]["lang"]=="ja": 24 #if(re.search(u'[一-龠]+|[ぁ-ん]+|[ァ-ヴー]+', tweet["text"])) and tweet['lang']=='ja': 25 #tweetを取得する 26 f_tweet = open("/home/LiLL/api_pack/tweet/"+str(datetime.datetime.now().strftime("%Y%m%d-%H"))+".json",'a') 27 #f_tweet = open(str(datetime.datetime.now().strftime("%Y%m%d-%H"))+".json", 'a') 28 str_tweet=data.decode("utf-8") 29 str_tweet = str_tweet + "\n" 30 f_tweet.write(str_tweet) 31 f_tweet.close() 32 except Exception as e: 33 print("error") 34 sys.stderr = open("errlog.log","a") 35 print(datetime.datetime.now(),'Encounted Exception:',e,file=sys.stderr) 36 sys.strerr=sys.__stderr__ 37 print(datetime.datetime.now(),'Encounted Exception:',e,file=sys.stderr) 38 pass 39 40 def on_error(self,status_code): 41 print(status_code) 42 43 sys.stderr = open("errlog.log","a") 44 print(datetime.datetime.now(),'Encounted Exception with status code:',status_code, file=sys.stderr) 45 sys.strerr=sys.__stderr__ 46 print(datetime.datetime.now(),'Encounted Exception with status code:',status_code, file=sys.stderr) 47 print("Unexpected error:", sys.exc_info()[0]) 48 49 return True 50 51 52 53printer = CustomStreamListener( 54 consumer_key, consumer_secret, 55 access_token, access_token_secret 56) 57printer.sample() 58
猫を含むツイート数の出力
python
1import json 2 nyankoTextList = [json.loads(tweet)["text"] for tweet in open("20220728-00.json", "r")] 3 4 kensaku_go = "猫" 5 print(sum([1 if kensaku_go in i else 0 for i in nyankoTextList]))
試したこと
猫を含むツイートの数ではなく、テキストを抽出したいです。
試したことは上記のプログラムを記述してみました。これを実行した結果132と出力されました。
補足情報(FW/ツールのバージョンなど)
仮想マシンVMWAREを使用してます
OSはubuntuです
ここにより詳細な情報を記載してください。
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
退会済みユーザー
2022/09/15 07:47
2022/09/15 08:17
退会済みユーザー
2022/09/15 08:33
退会済みユーザー
2022/09/15 08:45
2022/09/15 09:01