27
34

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Pythonでツイートを取得し外部ファイルへ保存、形態素解析をかけるスクリプト。

Last updated at Posted at 2015-04-10

ずっとTwitter API触っていたのでようやく形態素解析やってみようかと。
ここから色々発展させて遊べそうな予感がしてるところで以下がソース。

meca.py

#!/user/bin/env python
# -*- coding: utf-8 -*-
from requests_oauthlib import OAuth1Session
import json
import sys
import MeCab

C_KEY = "********************************"
C_SECRET = "********************************"
A_KEY = "********************************"
A_SECRET = "********************************"

def Home_timeline():
	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)
	for tweet in tweets:
		f = open("test.txt" , "aw")
		lists = (tweet["text"].encode("utf-8"))
			
		f.write(lists)
		f.flush()
		f.close()

def Mecab_file():	
	f = open("test.txt","rb")
	data = f.read()
	f.close()
	
	mt = MeCab.Tagger("-Ochasen")
	print mt.parse(data)


Home_timeline()
Mecab_file()

相変わらず美しくないですが、やってる処理は分かりやすいのではないかと。
f.flush()は必要かどうかわかりませんが念のため。
その後Mecabへ渡して形態素解析をかけてます。形態素解析の結果を表示するのはparseでやってますが、ここらへんも見やすく改造したいところ。

MeCabモジュールをインポートするにあたって、codecが干渉したのでimport sysだけにしてます。

27
34
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
27
34

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?