data

[ R 프로그래밍 ] 미세먼지관련 소셜키워드 분석

갬짱 2024. 8. 27. 00:25
# 패키지설치, 사전설정
setwd("c:\\temp")  
install.packages("KoNLP") 
install.packages("wordcloud") 
install.packages("stringr")

library(stringr)
library(KoNLP)  
library(wordcloud)
useSejongDic()

 

# 데이터 불러오기
data1 <- readLines('미세먼지_지식인.txt')   
head(data1,10)

 

# 중복제거 및 명사리스트화
data1 <- unique(data1)  # 중복행(줄) 데이터 제거
data2 <- str_replace_all(data1, "[^[:alpha:][:digit:][:blank:]]" , " " ) # 특수문자 제거

data3 <- extractNoun(data2)	# 각 줄(행)별로 명사추출
head(data3,5)

 

# 불용어 제거 및 단어 정제 하기(1)
data4 <- unlist(data3)
data5 <- gsub("\\^", "", data4) 
data5 <- gsub("PM2", "PM2.5", data5)
data5 <- gsub("아토", "아토피", data5)
data5 <- gsub(paste(c("미세", "먼지","미세먼지"),collapse='|'),"미세먼지", data5)

# 임시 집계하여 추출된 키워드 확인
data6 <- Filter(function(y) {nchar(y) <= 10 & nchar(y) >1 },data5)
wordcount <- table(data6)
head(sort(wordcount, decreasing=T),100)

 

# 불용어 제거 및 단어 정제 하기(2)
txt <- readLines("미세먼지gsub.txt")
txt

cnt_txt <- length(txt)
cnt_txt

for ( i in 1:cnt_txt ){
      data6 <- gsub((txt[i]),"", data6)   
}

# 집계
data7 <- Filter(function(y) {nchar(y) <= 10 && nchar(y) >1 },data6)
wordcount2 <- table(data7)
head(sort(wordcount2, decreasing=T),100)

 

# 시각화
par(oma=c(0.1,0.1,0.1,0.1)) # 출력될 화면의 여백 크기 지정하기
palete <- brewer.pal(7,"Set1")

wordcloud(names(wordcount2),freq=wordcount2,scale=c(5,1),rot.per=0.25,min.freq=10,
random.order=F,random.color=T,colors=palete)

# 생성된 워드 클라우드 작업 디렉토리에 저장
savePlot("수험번호_이름.png" , type="png")