![]() |
ノート/テキストマイニング/twitter-DB-LIKEhttps://pepper.is.sci.toho-u.ac.jp:443/pepper/index.php?%A5%CE%A1%BC%A5%C8%2F%A5%C6%A5%AD%A5%B9%A5%C8%A5%DE%A5%A4%A5%CB%A5%F3%A5%B0%2Ftwitter-DB-LIKE |
![]() |
訪問者数 872 最終更新 2012-10-21 (日) 15:24:37
SQL構文のうちの、LIKEを使って、「XXを含むツイート」を数えてみる
まず、LIKEの使い方は
SELECT text FROM <table> WHERE text LIKE '%<文字列>%'
但し、%の部分は任意文字列にマッチする
マッチするレコード(=ツイート)を取り出すプログラムは下記の通り。
#!/usr/bin/env python # -*- coding: utf-8 -*- # dbcountwithLIKE.py # import sys import codecs import time import MySQLdb import string from dbinit import dbinit sys.stdout = codecs.getwriter('utf_8')(sys.stdout) con = dbinit() # 自作関数dbinitはmySQLdbconnect(db, host, port, user, passwd)を呼ぶ。 cur = con.cursor() tablename = 'tw12102112' mystring = u'%電車%' # LIKEの対象文字列 #mystring = u'%今日%' s = "SELECT text FROM " + tablename + " WHERE text LIKE '" + mystring.encode('utf_8') + "'" cur.execute(s) r = cur.fetchone() while r != None: print "---" + r[0].encode('utf_8') r = cur.fetchone() cur.close() con.close()
もちろん、データベースからすべてのツイートを順繰りに取り出してからそれぞれをPython内でいろいろな処理をしてもよいのだが、SQLの機能を使ってみるとこうなるという例。
この方法で、文字列XXを含むツイートの数を数える(SQLに数えさせる)には、
SELECT COUNT(*) FROM <table> WHERE text LIKE '%<文字列>%'
をすればよい。
SQLの結果はカウント数(int)なので、printするにはstrを取ってやった方がいい。
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys import codecs import time import MySQLdb import string from dbinit import dbinit sys.stdout = codecs.getwriter('utf_8')(sys.stdout) con = dbinit() cur = con.cursor() tablename = 'tw12102112' mystring = u'%電車%' #mystring = u'%今日%' #s = "SELECT text FROM " + tablename + " WHERE text LIKE '" + mystring.encode('utf_8') + "'" s = "SELECT COUNT(*) FROM " + tablename + " WHERE text LIKE '" + mystring.encode('utf_8') + "'" # ここを書き換えた cur.execute(s) r = cur.fetchone() while r != None: print str(r[0]).encode('utf_8') # printにstrを噛ませた r = cur.fetchone() cur.close() con.close()