LoginSignup
8
4

More than 3 years have passed since last update.

tweet.jsの展開とか(json.loadsとeval)(Python)

Last updated at Posted at 2020-02-07

こんにちは、初投稿失礼します。
去年(2019年)あたりからcsv形式でダウンロードすることができなくなってしまいましたが、tweet.js,tweet-part<任意の自然数>.jsなどから、まずは"自分のツイート"のツイート"時間"と"テキスト"を抽出したいということで書いていきたいと思います。
~同じことを書いている人がいなかったので....クソ見にくいコードですがどうぞ~。

tweet.jsの場合、

read_js.py
#同じディレクトリにtweet.jsを入れてください
#MeCabをインストールしている場合にはコメントアウトを外すと分かち書きされたものが取り出されます。
import re
import datetime
import json
#import MeCab
tw_open = open("tweet.js","r",encoding="utf-8")
tw_time = open("tweet_mytext_time.txt","a",encoding="utf-8")
tw_a = open("tweet_mytext.txt","a",encoding="utf-8")
#tw_mecab = open("tweet_mytext_mecab.txt","a",encoding="utf-8")
twr = tw_open.read()
twr = re.sub("window.YTD.tweet.part0 = ","",twr)
twrj=json.loads(twr)
big=[]
small=[]
#mecab = MeCab.Tagger ("-Owakati")

for n in range(len(twrj)):
 tw=eval(str(twrj[n]["tweet"]))
 twf=str(tw["full_text"])
 twf=re.sub(r"https?://[\w/:%#\$&\?\(\)~\.=\+\-…]+","",twf)
 twf=twf.replace("\n","")
 twc=str(tw["created_at"])
 tim=datetime.datetime.strptime(twc,"%a %b %d %H:%M:%S %z %Y").replace(tzinfo=None)
 tim_r=str(tim).replace(" ","_")
 small=[]
 twf_b=twf.split(":")[0] 
 if not "RT" in twf_b:
  if not "@" in twf_b:
   small.append(str(tim.timestamp()).replace(".0",""))
   small.append(tim_r)
   small.append(twf)
   big.append(small)
small=[]

big.sort(key=lambda x: x[1],reverse=True)

for num in range(len(big)):
 tw_a.write(big[num][2]+"\n")
 tw_time.write(big[num][1]+" "+big[num][2]+"\n")
 #text=big[num][2]
 #text_m = mecab.parse(text)
 #tw_mecab.write(str(text_m))

tweet-part1.js、Mecabもある場合は、

read_js.py
import re
import datetime
import json
import MeCab
tw_open = open("tweet.js","r",encoding="utf-8")
tw1_open = open("tweet-part1.js","r",encoding="utf-8")
tw_time = open("tweet_mytext_time.txt","a",encoding="utf-8")
tw_a = open("tweet_mytext.txt","a",encoding="utf-8")
tw_mecab = open("tweet_mytext_mecab.txt","a",encoding="utf-8")
twr = tw_open.read()
tw1r = tw1_open.read()
twr = re.sub("window.YTD.tweet.part0 = ","",twr)
tw1r = re.sub("window.YTD.tweet.part1 = ","",tw1r)
twrj=json.loads(twr)
tw1rj=json.loads(tw1r)
big=[]
small=[]
mecab = MeCab.Tagger ("-Owakati")


for n in range(len(twrj)):
 tw=eval(str(twrj[n]["tweet"]))
 twf=str(tw["full_text"])
 twf=re.sub(r"https?://[\w/:%#\$&\?\(\)~\.=\+\-…]+","",twf)
 twf=twf.replace("\n","")
 twc=str(tw["created_at"])
 tim=datetime.datetime.strptime(twc,"%a %b %d %H:%M:%S %z %Y").replace(tzinfo=None)
 tim_r=str(tim).replace(" ","_")
 small=[]
 twf_b=twf.split(":")[0] 
 if not "RT" in twf_b:
  if not "@" in twf_b:
   small.append(str(tim.timestamp()).replace(".0",""))
   small.append(tim_r)
   small.append(twf)
   big.append(small)
small=[]

for n in range(len(tw1rj)):
 tw1=eval(str(tw1rj[n]["tweet"]))
 twf1=str(tw1["full_text"])
 twf1=re.sub(r"https?://[\w/:%#\$&\?\(\)~\.=\+\-…]+","",twf1)
 twf1=twf1.replace("\n","")
 twc1=str(tw1["created_at"])
 tim1=datetime.datetime.strptime(twc1,"%a %b %d %H:%M:%S %z %Y").replace(tzinfo=None)
 tim_r1=str(tim1).replace(" ","_")
 small=[]
 twf_b1=twf1.split(":")[0] 
 if not "RT" in twf_b1:
  if not "@" in twf_b1:
   small.append(str(tim1.timestamp()).replace(".0",""))
   small.append(tim_r1)
   small.append(twf1)
   big.append(small)

#print(big)
big.sort(key=lambda x: x[1],reverse=True)
for num in range(len(big)):
 tw_a.write(big[num][2]+"\n")
 tw_time.write(big[num][1]+" "+big[num][2]+"\n")
 text=big[num][2]
 text_m = mecab.parse(text)
 tw_mecab.write(str(text_m))

これを実行すると、

tweet_mytext.txt
テキスト
.....
tweet_mytext_time.txt
2020-01-19_05:47:57  テキスト
.....

となるはずです。

説明

基本的なところ()は置いておいて、JSON内の引用符をどう処理するかでだいぶ苦労しましたが、

twrj=json.loads(twr)
tw=eval(str(twrj[n]["tweet"]))

などのところで、openとreadで文章全体を読み込んで余分なヘッダーを取り除いて、json.loads(文字型)で辞書型に変換しているようです。
そこからevalで更に辞書型のtweetの値を辞書として変換しています。

{'tweet': {'retweeted': False, 'source': '<a href="http://twitter.com/download/android" rel="nofollow">Twitter for Android</a>', 'entities': {'hashtags': [], 'symbols': [], 'user_mentions': [{'name': 'Saidjon', 'screen_name': 'noppo6', 'indices': ['3', '10'], 'id_str': '240638809', 'id': '240638809'}], 'urls': []}, 'display_text_range': ['0', '140'], 'favorite_count': '0', 'id_str': '1218787465110024192', 'truncated': False, 'retweet_count': '0', 'id': '1218787465110024192', 'created_at': 'Sun Jan 19 06:49:10 +0000 2020', 'favorited': False, 'full_text': 'RT @noppo6: サマルカンドが青いのは、独立後観光客を呼び込むために青く塗ったから。ほとんど遺跡破壊のレベル。これでサマルカンドを「青の都」と讃えている日本のガイドブックやメディアはおめでたい限り。この素朴なサマルカンドもこれはこれでいいと思う。\nにしても、シャーヒズィ…', 'lang': 'ja'}}

自分がさっき取得したJSONは例えばこうなっていました。

Q.自分のツイートかどう判断している?
A.RTの場合はコロンで、0番目にRTと@が含まれているため、それで判断しています

ここまで書くだけ書いてみましたが、仮に役立ったようであれば嬉しいです。ツイッター(@kenkensz9)にいつもいるので何かあればどうぞ
よろしければいいねお願いします!

8
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
4