トップ 一覧 検索 ヘルプ RSS ログイン

getTweet2の変更点

Base Text vs. New Text
1
1*RでTwitterからデータをとってくる
2**参考 http://cran.r-project.org/web/packages/twitteR/vignettes/twitteR.pdf
3**http://www.atmarkit.co.jp/fcoding/articles/stat/05/stat05a.html その後Twitterの認証方法が変更になったため、使えない部分が多いので参考までに。
4
5*まずインストール    一度すればok
6 install.packages('XML')
7
8
9*処理方法
10 library(XML)
11 #********* Windowsか否かを判定して文字コード変換も自動で行うように改良
12 #まず必要なサブルーチンを定義
13 ##検索語と 取得ページ数を指定 多分最大15ページ(ページあたり100)
14 #必要な情報を抽出してデータフレームに
15 searchTweet2<-function(sword, npages){
16 (a<-Sys.info())
17 (fg.win<-length(grep("WIND.*",a,ignore.case =T))!=0) #WinならばTRUEになる
18 #サーチ語の文字コード変換
19 #if(fg.win) (sword<-iconv(sword,from="UTF-8",to="WINDOWS-932"))
20 #if(fg.win) (sword<-iconv(sword,to="UTF-8"))
21 twitter_q <- URLencode(sword) # search parameter
22 mydata.xmls <- character(0)
23
24 for (page in c(1:npages))
25 {
26 # URL作成
27 (twitter_url = paste('http://search.twitter.com/search.atom?q=',twitter_q,'&locale=ja&lang=ja&rpp=100&page=', page, sep=''))
28 mydata.xml <- xmlParseDoc(twitter_url, asText=F,encoding = "UTF-8")
29 pdate <- xpathSApply(mydata.xml, '//s:entry/s:published', xmlValue, namespaces =c('s'='http://www.w3.org/2005/Atom'))
30
31 if(length(pdate)==0){
32 print(list(sword,"ヒットしませんでした"))
33 pdate<-user_name<-user_rname<-user_url<-messages<-NULL
34    }
35 else{
36 authors <- xpathSApply(mydata.xml, '//s:entry/s:author', xmlValue, namespaces =c('s'='http://www.w3.org/2005/Atom'))
37 authors <- xpathSApply(mydata.xml, '//s:entry/s:author', xmlValue, namespaces =c('s'='http://www.w3.org/2005/Atom'))
38 authors2<-lapply(authors,function(x) gsub("^\n","",x) )
39 authors2<-lapply(authors,function(x) gsub("\n)",")",x) ) #ユーザー名の中に\nが使われている
40 authors2<-lapply(authors2,function(x) gsub(" ","",x) )
41 authors3<-lapply(authors2,function(x) unlist(strsplit(x,"\n")))
42 authors4<-as.data.frame(authors3)
43
44 usernam<-t(authors4[2,]);rownames(usernam)<-NULL
45 #explorer_taku(TAKU) 基本はこのようになっているが
46 #"nya_harinezumi(にゃ~(よばりん)@美菜子病)   のようにrユーザー名にも(があるのもいる
47
48 user_name<-unlist(lapply(usernam,function(x) gsub('\\(.*\\)$',"",as.character(x)))) #ユーザー名
49 user_rname<-substr(usernam,nchar(user_name)+2,nchar(usernam)-1)
50 (user_url<-t(authors4[3,]));rownames(user_url)<-NULL #URL
51
52 messages <- xpathSApply(mydata.xml, '//s:entry/s:title', xmlValue, namespaces =c('s'='http://www.w3.org/2005/Atom'))
53 messages<-sapply(messages,as.character)
54
55 #windows 932コードの場合、それに変換
56 if(fg.win){
57 (messages<-sapply(messages,function(x) iconv(x,from="UTF-8",to="WINDOWS-932") ))
58 (user_rname<-sapply(user_rname,function(x) iconv(x,from="UTF-8",to="WINDOWS-932") ))
59 }
60 }
61 dat<-data.frame(pdate, user_name, user_rname, user_url, messages)
62 names(dat)<-c("pdate", "user_name", "user_rname", "user_url", "messages")
63 if(page==1){dat0<-dat}
64 else{
65 dat0 <- rbind(dat0, dat)
66 }
67    mydata.xmls <- list(mydata.xmls, mydata.xml)
68 }
69 print(dim(dat0))
70 print(names(dat0))
71 return(list(dat0, mydata.xmls))
72 }
73 #ここまでをコピーペーストすると定義される。
74
75*使い方
76**検索語を"   "の中に"この例では masason と RT、  取得ページ数 指定 多分最大15ページ(ページあたり100)
77**Windowsの場合、日本語キーワードだとエラーになるようなので、ユーザー名など半角英数字で指定。
78***ユーザー名の切り出しがうまくいかずエラーになることもあるので、別の人などでトライしてみて下さい。
79***sdat<-searchTweet2("孫正義 RT",2)
80***sdat<-searchTweet2("ファミリーマート",2)
81***sdat<-searchTweet2("family_mart RT",2)
82 sdat<-searchTweet2("masason RT",2)
83
84 sText<-sdat[[1]] #これがデータ
85 sText[1:5,] #1-5番目までをみてみる
86 dim(sText)#いくつメッセージをとってこれたか
87 names(sText)#含まれる変数名を表示
88 #"pdate" "user_name" "user_rname" "user_url" "messages" 日付、ユーザー名1 ユーザー名2 URL メッセージ
89 table(substr(sText$pdate,1,10))#日付毎に集計
90 table(sText$user_rname)#user_rname毎に集計
91
92 #保存
93 save(sText,file="0sText.rda")
94
95*おまけ 文字の内容を判定するためのルーチン(文字コードWIN変換はこの場合不要。。。
96 #---------------
97 #dat の中に dicに含まれている文字列があるかを判定
98 #datについてはWIN-932に変換されていることを前提
99 #dicについては変換されていないので、ここで変換>この場合不要であった
100 #---------------
101 parseWords<-function(dat,dic){
102 # (a<-Sys.info()) #文字コード変換
103 #(fg.win<-length(grep("WIND.*",a,ignore.case =T))!=0) #WinならばTRUEになる
104 #if(fg.win){dic<-iconv(dic,from="UTF-8",to="WINDOWS-932")}
105
106 fg.word<-rep(0, length(dat))
107 no.mes<- grep(dic,dat,ignore.case = T)#dic内にある 単語を含むと TRUE そうでないとFALSEになる
108 fg.word[no.mes]<-1
109 print(c("辞書は",dic))
110 print(list("キーワードを含むメッセージ" ))
111 print(dat[no.mes])
112 print(c("ヒットしたメッセージの数",sum(fg.word))) #TRUEになったメッセージをみてみる
113 return(fg.word) #フラグだけを返す
114 }
115*使い方
116 #ポジティブ。ネガティブと判定するためのキーワードを | でつないで定義  これのいずれかを含むかを判定する
117 sText$messages #一度、ざっとメッセージをみて、重要そうなものをみつける
118 dic.positive<-"いい|好き|すき|きれい|よい|おいしい"
119 posflag<-parseWords(sText$messages,dic.positive) #メッセージのうちキーワードが含まれていると1になるフラグ
120 posflag
121
122 dic.negative<-"だめ|嫌い|きらい|きたない|よくない|まずい|ひどい|恥ずかしい|やめろ"
123 negaflag<-parseWords(sText$messages,dic.negative)
124 negaflag
125 #それぞれを sTextに変数として入れる
126 sText$posflag<-posflag
127 sText$negaflag<-negaflag
128 #含まれるものを表示する
129 sText[sText$posflag==1,]
130 sText[sText$negaflag==1,]
131 #これらの結果をみながら 辞書内のキーワードが適切かを調整する
132 #よい だと よいしょ 
133 #いい だと  どうでもいい も含まれる など微妙な問題がある。。
134
135
136
137
138*調査中
139**messageから @ユーザー名 部分をどうやって切り出すか?
140 sText$messages[1:3]
141 (RTs <-lapply(sText$messages[1:3],function(x) unlist(strsplit(as.character(x),"[@ :]"))))
142 #(RTs <-lapply(sText$messages[1],function(x) unlist(sub("![@.* ]","",x))))
143 #gregexpr("@.*[: ]",sText$messages[1])
144 #gregexpr("@.*[: ]",sText$messages[1])
145
146*参考) 文字コード変更コマンド Windows用  上のルーチンには入れてある
147 sText$messages[1]
148 iconv(sText$messages[1],from="UTF-8",to="WINDOWS-932")
149 (sText$mes2<-sapply(sText$messages,function(x) iconv(x,from="UTF-8",to="WINDOWS-932") ))
150
151*参考
152 #現在の文字コードを調べる
153 (syslocale0<-Sys.getlocale())
154 #処理をして文字化けするようならば、 下記にて文字コードを指定すると直るかも? Windowsでは指定不能
155 Sys.setlocale('LC_ALL','ja_JP.UTF-8')
156
157*参考 認証しないとダウンロードできるメッセージ数に上限があるが、認証するとこれが大きくなるらしい。
158**そのためのパッケージが下記のよう。誰か研究してみて下さい。twitterアカウントを登録して、さらに開発者として登録。
159 install.packages("ROAuth")
160 library(ROAuth)
161 ??ROAuth
162
163*参考)システム情報を取得 (Winならば文字コードを変換するようにしたい)
164 (a<-Sys.info())
165 (fg.win<-length(grep("WIND.*",a,ignore.case =T))!=0) #WinならばTRUEになる
166
167*参考) 下記のようなXMLでデータが帰ってくるので、それから必要な部分を切り出している。
168 <entry>
169 <id>tag:search.twitter.com,2005:81013205966667776</id>
170 <published>2011-06-15T15:00:28Z</published>
171 <link type="text/html" href="http://twitter.com/02111973/statuses/81013205966667776" rel="alternate"/>
172 <title>RT @rishikaw: RT @SoftBankCorp: 本日のエネルギーシフト勉強会における孫正義講演のアーカイブ映像はこちらからご覧ください。 http://ustre.am/:12AwV (iPhone http://ustre.am/:12AwY ) #energyjp</title>
173 <content type="html">&lt;b&gt;RT&lt;/b&gt; &lt;a href="http://twitter.com/rishikaw"&gt;@rishikaw&lt;/a&gt;: &lt;b&gt;RT&lt;/b&gt; &lt;a href="http://twitter.com/SoftBankCorp"&gt;@SoftBankCorp&lt;/a&gt;: 本日のエネルギーシフト勉強会における孫正義講演のアーカイブ映像はこちらからご覧ください。 &lt;a href="http://ustre.am/:12AwV"&gt;http://ustre.am/:12AwV&lt;/a&gt; (iPhone &lt;a href="http://ustre.am/:12AwY"&gt;http://ustre.am/:12AwY&lt;/a&gt; ) &lt;a href="http://search.twitter.com/search?q=%23energyjp" onclick="pageTracker._setCustomVar(2, 'result_type', 'recent', 3);pageTracker._trackPageview('/intra/hashtag/#energyjp');"&gt;#energyjp&lt;/a&gt;</content>
174 <updated>2011-06-15T15:00:28Z</updated>
175 <link type="image/png" href="http://a2.twimg.com/profile_images/1277806313/52d05d41-fb47-4625-951b-7d7e82d776f2_normal.png" rel="image"/>
176 <twitter:geo>
177 </twitter:geo>
178 <twitter:metadata>
179 <twitter:result_type>recent</twitter:result_type>
180 </twitter:metadata>
181 <twitter:source>&lt;a href="http://twipple.jp/" rel="nofollow"&gt;ついっぷる for iPhone&lt;/a&gt;</twitter:source>
182 <twitter:lang>ja</twitter:lang>
183 <author>
184 <name>02111973 (akaおんちゃん)</name>
185 <uri>http://twitter.com/02111973</uri>
186 </author>
187 </entry>
188
189*以下はふるいもの
190 **練習 自分の興味のある人のユーザー名(titter)を入力して上記を実行してみる。
191*練習  興味のある人のツイートをダウンロードしてみる nも変更してみてどうなるか? 300や1000ぐらいにするとどうなるか?
192*練習  興味のある検索語を指定してダウンロードしてみる。検索語やnも変更してみてどうなるか? 300や1000ぐらいにするとどうなるか?
193**検索語に RT を追加すると その語を含むRTがとれるようなので、これをうまく使えば、アカウント間の関係を把握できそう。その他、ツイッターの検索のオプションを指定してみてください。
194**参考)マニュアルによると下のように開始、終了日を指定できるはずだが、うまくいかない感じ。nやlangなどの与え方によってはとれるかもしれないので、いろいろトライしてみてください。
195**全体的に今回のプロジェクトでこのデータを使えそうか否かを考察。
196
197 sText$messages[1]<-"RT @softbank_ichiro: 岡田氏は、再生エネルギー法案をどう考えているのか!?単に政局のみに終始しては、日本は道を誤る!!QT: 政局:「再生エネ法も」に自民不信…退陣条件追加 - 毎日jp(毎日新聞) http://t.co/taCJRLj #genpatsu @masason"
198
199 txt<-sText$messages[1]
200 (a<-unlist(gregexpr("@",txt)))
201 (b<-unlist(gregexpr("[ :]",txt)))
202 retweeter<-character(0)
203 for (i in seq(1,length(a))){
204     start<-a[i]
205     end<-min(b[b>start])
206 (retw<-substr(txt,start,end-1))
207 retweeter<-list(    retweeter, retw)
208 }
209 unlist(retweeter)
210
diff view generated by jsdifflib