Text Mining

hottogi·2023년 1월 4일
0

1. 토픽분석

(1) 패키지 로딩

library(KoNLP)
install.packages("hash")
install.packages("tau")
install.packages("devtools")
install.packages("RSQLite")
library(KoNLP)
library(tm)
library(wordcloud)

(2) 텍스트 자료 가져오기

facebook <- file("facebook_bigdata.txt", encoding = "UTF-8")
facebook_data <- readLines(facebook)
head(facebook_data)

(3) 세종 사전에 단어 추가하기

user_dic <- data.frame(term = c("R 프로그래밍", "페이스북", "홍길동", "소셜네트워크"),
 tag = 'ncn')
buildDictionary(ext_dic = "sejong", user_dic = user_dic)

(4) R 제공 함수로 단어 추출하기

paste(extractNoun('홍길동은 많은 사람과 소통을 위해서 소셜네트워크에
가입하였습니다.'),
 collapse = " ")

(5) 단어 추출을 위한 사용자 함수 정의하기

# 단계 1: 사용자 정의 함수 작성
exNouns <- function(x) {paste(extractNoun(as.character(x)), collapse = " ") }

# 단계 2: exNouns() 함수를 이용하여 단어 추출
facebook_nouns <- sapply(facebook_data, exNouns)
facebook_nouns[1]

(6) 추출된 단어를 대상으로 전처리하기

# 단계 1: 추출된 단어를 이용하여 말뭉치(Corpus) 생성
myCorpus <-Corpus(VectorSource(facebook_nouns))
# 단계 2: 데이터 전처리
# 단계 2-1: 문장부호 제거
myCorpusPrepro <- tm_map(myCorpus, removePunctuation)
# 단계 2-2: 수치 제거
myCorpusPrepro <- tm_map(myCorpusPrepro, removeNumbers)
# 단계 2-3: 소문자 변경
myCorpusPrepro <- tm_map(myCorpusPrepro, tolower)
# 단계 2-4: 불용어 제거
myCorpusPrepro <- tm_map(myCorpusPrepro, removeWords, stopwords('english'))
# 단계 2-5: 전처리 결과 확인
inspect(myCorpusPrepro[1:5])

(7) 단어 선별(2 ~ 8 음절 사이 단어 선택)하기

# 단계 1: 전처리된 단어집에서 2 ~ 8 음절 단어 대상 선정
myCorpusPrepro_term <-
 TermDocumentMatrix(myCorpusPrepro, 
 control = list(wordLengths = c(4, 16)))
myCorpusPrepro_term
# 단계 2: matrix 자료구조를 data.frame 자료구조로 변경
myTerm_df <- as.data.frame(as.matrix(myCorpusPrepro_term))
dim(myTerm_df)

(8) 단어 출현 빈도수 구하기

wordResult <- sort(rowSums(myTerm_df), decreasing = TRUE)
wordResult[1:10]

(9) 불용어 제거하기

# 단계 1: 데이터 전처리
# 단계 1-1: 문장부호 제거
myCorpusPrepro <- tm_map(myCorpus, removePunctuation)
# 단계 1-2: 수치 제거
myCorpusPrepro <- tm_map(myCorpusPrepro, removeNumbers)
# 단계 1-3: 소문자 변경
myCorpusPrepro <- tm_map(myCorpusPrepro, tolower)
# 단계 1-4: 제거할 단어 지정
myStopwords = c(stopwords('english'), "사용", "하기")
# 단계 1-5: 불용어 제거
myCorpusPrepro <- tm_map(myCorpusPrepro, removeWords, myStopwords)
#단계 2: 단어 선별과 평서문 변환
myCorpusPrepro_term <-
 TermDocumentMatrix(myCorpusPrepro,
 control = list(wordLengths = c(4, 16)))
myTerm_df <- as.data.frame(as.matrix(myCorpusPrepro_term))
# 단계 3: 단어 출현 빈도수 구하기
wordResult <- sort(rowSums(myTerm_df), decreasing = TRUE)
wordResult[1:10]

(10) 단어 구름에 디자인(빈도수, 색상, 위치, 회전 등) 적용하기

# 단계 1: 단어 이름과 빈도수로 data.frame 생성
myName <- names(wordResult)
word.df <- data.frame(word = myName, freq = wordResult)
str(word.df)
# 단계 2: 단어 색상과 글꼴 지정
pal <- brewer.pal(12, "Paired")
# 단계 3: 단어 구름 시각화
wordcloud(word.df$word, word.df$freq, scale = c(5, 1), 
 min.freq = 3, random.order = F, 
 rot.per = .1, colors = pal, family = "malgun")

Wordcloud2

library(devtools)
library(wordcloud2)
wordcloud2(data = demoFreq)

profile

0개의 댓글