1
3

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 3 years have passed since last update.

Covid-19のソーシャル分析その2 感情分析

Posted at

##Covid-19のソーシャル分析その2 感情分析
トランプ大統領のツイートを抽出し、感情分析を実施してみた。
おそらく時系列でみてみると彼の焦りや不満点が見えてきて
かつ、次に実施される政策の方向性がある程度見えてくるんじゃないか
と思うので各で分析を深めてもらいたい。

##Rによる感情分析

emotion_analysis.rb
#ライブラリー
library("twitteR")
library("lubridate")
library("ggplot2")
library("ggmap")
library("stringr")
library("tm")
library("RColorBrewer")
library("wordcloud")
library("syuzhet")
#APIkey入力・認証
#参考:https://www.itti.jp/web-direction/how-to-apply-for-twitter-api/
APIKey <- ""
APISecret <- ""
accessToken <- ""
accessSecret <- ""
options(httr_oauth_cache = TRUE)
setup_twitter_oauth(APIKey, APISecret, accessToken, accessSecret)
#ツイート取得
extractTimelineTweets <- function(username,tweetCount){
  # timeline tweets
  twitterUser <- getUser(username)
  tweets = userTimeline(twitterUser,n=tweetCount)
  tweets.df = twListToDF(tweets)
  tweets.df$text <- sapply(tweets.df$text,function(x) iconv(x,to='UTF-8'))
  
  return(tweets.df)
}

tweetsDF <- extracTimelineTweets("POTUS",1500)

#前処理作業
nohandles <- str_replace_all(tweetsDF$text, "@\\w+","")
wordCorpus <- Corpus(VectorSource(nohandles))
wordCorpus <- tm_map(wordCorpus, removePunctuation)
wordCorpus <- tm_map(wordCorpus, removeWords, stopwords("english"))
wordCorpus <- tm_map(wordCorpus, removeWords, c("amp"))
wordCorpus <- tm_map(wordCorpus, stripWhitespace)
#wordcloud
pal <- brewer.pal(9,"YlGnBu")[-(1:4)]
wordcloud(words = wordCorpus,
          scale =c(5,0.1),
          max.words = 1000,
          random.order = FALSE,
          rot.per =0.35,
          use.r.layout = FALSE,
          colors =pal)

#感情スコアー
TweetSentiments <- get_sentiment(tweetsDF$text,method ="syuzhet")
tweets <- cbind(tweetsDF, TweetSentiments)
#グラフ1
qplot(tweets$TweetSentiments)+
  theme(legend.position ="none")+
  xlab("sentiment score")+
  ylab("Number of Tweets")+
  ggtitle("Tweets by sentiment Score")

#グラフ2感情カテゴリー関数
encodeSentiment <- function(x){
  if (x <= -0.5){
    "very negative"
  }else if (x< 0){
    "negative"
  }else if(x ==0) {
    "neutral"
  } else if (x <0.5){
    "positive"
  }else{ # x>=0.5
    "very positive"
    }
}


##参考文献
**Package Syuzhet**
https://cran.r-project.org/web/packages/syuzhet/vignettes/syuzhet-vignette.html
1
3
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
1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?