2014년 4월 17일 목요일

[Using R] Sentiment Analysis Sample Source

# 아래 내용은 이전 포스팅인
트위터 글(데이터) 수집하기 에서 만들어진것이 R실행 코드에서 연결되어야 실행 가능 합니다.

install.packages("plyr")
library(plyr)

hilton.text <-laply(hilton.tweets,function(t)t$getText())
head(hilton.text,3)

#긍정 단어 파일 스캔
pos.word=scan("positive-words.txt",what="character",comment.char=";")

#부정 단어 파일 스캔
neg.word=scan("negative-words.txt",what="character",comment.char=";")

#수작업으로 추가 할수도 있음 (Sample)
pos.words<-c(pos.word,"upgrade")
neg.words<-c(neg.word,"wtf","wait","waiting","epicfail","mechanical")


#
install.packages("plyr")
install.packages("stringr")
library(plyr)
library(stringr)

score.sentiment =
function(sentences, pos.words, neg.words, .progress='none')
{
  require(plyr)
  require(stringr)

  # we got a vector of sentences. plyr will handle a list
  # or a vector as an "l" for us
  # we want a simple array ("a") of scores back, so we use
  # "l" + "a" + "ply" = "laply":
  scores = laply(sentences, function(sentence, pos.words, neg.words) {
 
    # clean up sentences with R's regex-driven global substitute, gsub():
    sentence = gsub('[[:punct:]]', '', sentence)
    sentence = gsub('[[:cntrl:]]', '', sentence)
    sentence = gsub('\\d+', '', sentence)

    # and convert to lower case:
    sentence = tolower(sentence)
 
    # split into words. str_split is in the stringr package
    word.list = str_split(sentence, '\\s+')

    # sometimes a list() is one level of hierarchy too much
    words = unlist(word.list)
 
    # compare our words to the dictionaries of positive & negative terms
    pos.matches = match(words, pos.words)
    neg.matches = match(words, neg.words)
 
    # match() returns the position of the matched term or NA
    # we just want a TRUE/FALSE:
    pos.matches = !is.na(pos.matches)
    neg.matches = !is.na(neg.matches)
 
    # and conveniently enough, TRUE/FALSE will be treated as 1/0 by sum():
    score = sum(pos.matches) - sum(neg.matches)
 
    return(score)
  }, pos.words, neg.words, .progress=.progress )

  scores.df = data.frame(score=scores, text=sentences)
  return(scores.df)
}

#함수 실행
hilton.text<-hilton.text[!Encoding(hilton.text)=="UTF-8"]
hilton.scores=score.sentiment(hilton.text,pos.words,neg.words,.progress='text')

#실행결과 값을 히스토그램으로 표현
hist(hilton.scores$score)
hilton.scores$hotel='Hilton'
hilton.scores$code='HL'


댓글 없음:

댓글 쓰기

언제 부터 였던가 생각해보니 아르바이트 겸 외부 컨설팅을 의뢰 받고 맥북 프로를 처음 써봤을 때 부터 였던 것 같다. 지금은 거의 대부분의 작업을 맥으로 작업을 하다 보니 윈도우에서만 실행되는 일부 프로그램들 때문과 회사 내부 ERP프로그램이 윈도우 ...