このページは、TwitterBot影響分析 本から参照されています。
前提:ツイートアクティビテイのエクスポートデータだけを集めたcsvdata/というディレクトリを用意してある。
前提:python3 (2016/07/10
Python3に統一しました。)
home以下の任意のディレクトリを起点とする。
起点の配下にcsvdataというディレクトリを作り、
そこにツイッターアナリティクスからエクスポートしたcsvをファイル名を変更せず置いておく。
【p3_tweet_analyzer.py】を作成する。
# -*- coding: utf-8 -*-
import pandas as pd
# 指定ディレクトリのCSVを全て読み込む。
import os
theCSVdirectory = './csvdata/'
files = os.listdir(theCSVdirectory)
theStack = []
for file in files:
print(file)
theStack.append(pd.read_csv(theCSVdirectory + file, encoding="UTF-8",
parse_dates=[u"時間"]))
print("ファイル数:" + str(len(files)))
print("PDs:" + str(len(theStack)))
# 統合したテーブルを作る。
theTable = pd.concat(theStack, ignore_index=True)
# 時間変換
from pandas.tseries.offsets import *
theTable[u"時間"] = theTable[u"時間"] + DateOffset(hours=9)
print(theTable[u"時間"])
theTable.index.names = ["No."]
theTable.ix[:,[u"インプレッション",u"エンゲージメント"]].to_csv('pandasforjubatus.csv')
# python3 p3_tweet_analyzer.py
jubatusに分析させるためのcsvが生成されたことを確認する。
# tail pandasforjubatus.csv
【anomaly_conf.json】を作成する。
{
"converter" : {
"string_rules" : [
{ "key" : "*", "type" : "str", "sample_weight" : "bin" ,
"global_weight" : "bin" }
],
"num_rules" : [
{ "key" : "*", "type" : "num" }
]
},
"parameter" : {
"nearest_neighbor_num" : 3,
"reverse_nearest_neighbor_num" : 3,
"method" : "euclid_lsh",
"parameter" : {
"hash_num" : 512
}
},
"method" : "light_lof"
}
# cat anomaly_conf.json
※jubaanomalyのサービスを起動させる。
# jubaanomaly --configpath anomaly_conf.json
&
【p3_jubaanomalyForTweetAnalyze.py】を作成する。
# -*- coding: utf-8 -*-
import csv
path = 'pandasforjubatus.csv'
theCSV = csv.DictReader(open(path), delimiter = ',')
import jubatus
from jubatus.common import Datum
client = jubatus.Anomaly('127.0.0.1', 9199, 'meh')
client.clear()
data = []
for row in theCSV:
feature_data = {}
for key, value in row.items():
if key == "No.":
continue
if value.isdigit():
feature_data[key] = float(value)
else:
feature_data[key] = value
data.append(feature_data)
theProgress = 0
for datum in data:
result = client.add(Datum(datum)).score
print("No.{p}:{f} => {s}".format(p=theProgress, f=str(datum),
s=result))
theProgress += 1
#python3 p3_jubaanomalyForTweetAnalyze.py