[]Python

追記

※最新のコード(全文)はgistに
http://gist.github.com/527326

ログ取得

定期的に近時190tweetsをログに保存

[cc lang='python']
import twitter

api = twitter.Api()
lists = api.GetUserTimeline('your_twitter_screen_name',190)

tweets = ""
for s in lists:
tweets += s.text

idfile = open('tweets.txt', 'w')
idfile.write(tweets.encode('utf-8'))
idfile.close()
[/cc]

Yahoo!形態素解析API

Yahoo!デベロッパーネットワークでアプリケーションIDを取得。形態素解析APIを利用。

各パラメータ等はhttp://developer.yahoo.co.jp/webapi/jlp/ma/v1/parse.html参照。

[cc lang='python']
def yahooParse(self,tweets):
pageurl = 'http://jlp.yahooapis.jp/MAService/V1/parse'
results = 'ma'
my_filter = '1|2|3|4|5|6|7|8|9|10|11|12|13'
params = urllib.urlencode({'appid':self.appid, 'results':results, 'filter':my_f
ilter, 'sentence':tweets})
html = urllib2.urlopen(pageurl, params)
return html
[/cc]

帰ってきた結果(html)をBeautifulSoupモジュールを利用してパース。分解された形態素と品詞のタプルを要素としてリスト生成。

[cc lang='python']
soup = BeautifulSoup(html.read())
wordlist = [(w.surface.string, w.pos.string) for w in soup.ma_result.word_list]
[/cc]

マルコフ連鎖

マルコフ連鎖でセンテンスを生成。文が不自然にならないように文頭から特定の品詞を除いている。文末は操作していないので改良の必要あり。1〜70回の範囲でランダムに連鎖する。

辞書markovはキーに2語(w1,w2)のタプルをもち、それぞれ形態素とその品詞のタプルとなっている。値はリストで、辞書に同一キーが存在するときにそれに続く語がどんどん追加されていく。

e.g.) markov = { ( (u'私', u'名詞'), (u'は', u'助詞') ) : [ (u'鳥', u'名詞'), (u'とても', u'副詞'), ...] }

ロジックは以下のページと同じものである。こちらの説明のほうがわかりやすい。

[cc lang='python']
def makeMarkov(self,wordlist):
markov = {}
w1 = (u'', u'')
w2 = (u'', u'')
for word in wordlist:
if w1[0] and w2[0]:
if(w1, w2) not in markov:
markov[(w1,w2)] = []
markov[(w1,w2)].append*1
w1, w2 = w2, word

count1 = 0
count2 = 0
sentence = u"error:文頭に適切な品詞なし"
while count1 < 50:
w1, w2 = random.choice(markov.keys())
poslist = [u'接尾辞',u'動詞',u'助詞',u'助動詞',u'特殊']
if w1[1] not in poslist:
sentence = w1[0] + w2[0]
cnt = random.randint(1,70)
while count2 < cnt:
tmp = random.choice(markov[(w1,w2)])
sentence += tmp[0]
w1, w2 = w2, tmp
count2 += 1
return sentence
break
return sentence
[/cc]

このsentenceをtweet

[cc lang='python']
api = twitter.Api(self.screen_name,self.password)
api.PostUpdates(sentence)
[/cc]

参考

  • MeCabとPythonでマルコフ連鎖を書いてみる(改) | Weboo! Returns.

  • PythonからYahoo!形態素解析APIを使う - 人工知能に関する断想録
  • *1:word[0], word[1]