Data Analysis

R/텍스트마이닝

[텍스트마이닝] 단어 빈도 분석 관련 연습문제

Holy_Water 2022. 11. 18. 13:19

Q1. speech_park.txt를 불러와 분석에 적합하게 전처리한 다음 띄어쓰기 기준으로 토큰화하세요.

 

라이브러리, 데이터 준비

library(dplyr)
library(stringr)
park <- file("dataset3/speech_park.txt", encoding = "UTF-8")
park_data <- readLines(park)

 

데이터 전처리 하기

park <- park_data %>%
  str_replace_all("[^가-힣]", " ") %>% # 한글만 남기기
  str_squish() %>% # 연속된 공백 제거
  as_tibble() 
park

 

띄어쓰기 기준으로 토큰화 하기

library(tidytext)
word <- park %>% unnest_tokens(input = value, output = word, token = 'words')
word

 

 

#Q2. 가장 자주 사용된 단어 20개를 추출하세요.

 

top20 <- word %>% count(word, sort = T) %>% head(20)
top20

 


#Q3. 가장 자주 사용된 단어 20개의 빈도를 나타낸 막대 그래프를 만드세요. 
#•그래프의 폰트는 나눔고딕으로 설정하세요.

 

폰트 설정

library(showtext)
font_add_google(name = "Nanum Gothic", family = "nanumgothic")
showtext_auto()

 

막대그래프 만들기

library(ggplot2)
X11()
ggplot(top20, aes(x = reorder(word, n), y = n)) +
  geom_col() +
  coord_flip () +
  geom_text(aes(label = n), hjust = -0.3) +
  labs(x = NULL) +
  theme(text = element_text(family = "nanumgothic"))