Data Analysis

R/텍스트마이닝

[텍스트마이닝] 단어 빈도 비교하기

Holy_Water 2022. 11. 21. 11:18

문재인 대통령 연설문 불러오기

library(dplyr)
raw_moon <- readLines("dataset3/speech_moon.txt", encoding = "UTF-8")
moon <- raw_moon %>% as_tibble() %>% mutate(president = "moon")

 

박근혜 대통령 연설문 불러오기

raw_park <- readLines("dataset3/speech_park.txt", encoding = "UTF-8")
park <- raw_park %>% as_tibble() %>% mutate(president = "park")

tibble 구조로 변환하고 연설문 구분 위해 대통령 이름 부여

 

 

데이터 합치기

bind_speeches <- bind_rows(moon,park) %>% select(president, value)

두 데이터를 행(세로) 방향으로 결합, 출력 결과 보기 편하게 select()로 변수 순서 바꾸기, 윗부분은 문재인 대통령, 아랫부분은 박근혜 전 대통령 연설문

 

 

집단별로 전처리 및 토큰화

library(stringr)
speeches <- bind_speeches %>% mutate(value = str_replace_all(value, "[^가-힣]", " "), value = str_squish(value))

한글 이외의 문자, 연속된 공백 제거,  bind_speeches는 tibble 구조이므로 mutate() 활용

 

 

형태소 분석기를 이용해 명사 기준 토큰화

library(tidytext)
library(KoNLP)
speeches <- speeches %>% unnest_tokens(input = value, output = word, token = extractNoun)
speeches

 

두 연설문의 단어 빈도 구하기

frequency <- speeches %>% count(president, word) %>% filter(str_count(word) > 1)

 

연설문에서 가장 많이 사용된 단어 추출하기

top10 <- frequency %>% group_by(president) %>% slice_max(n, n = 10)
head(top10,20)

dplyr::slice_max() : 값이 큰 상위 n개의 행을 추출해 내림차순 정렬

 

 

빈도 동점 단어 제외하고 추출하기

top10 <- frequency %>% group_by(president) %>% slice_max(n, n= 10, with_ties = F)
top10

president별 고빈도 단어 상위 10개 추출

 

 

막대 그래프 만들기

library(ggplot2)
ggplot(top10, aes(x = reorder(word, n),
                  y = n,
                  fill = president)) +
  geom_col() +
  coord_flip() +
  facet_wrap(~ president, # president별 그래프 생성
             scales = "free_y") # y축 통일하지 않음

변수의 항목별로 그래프만들기 - facet_wrap(),  ~ 뒤에 그래프를 나누는 기준 변수 입력

 

 

특정 단어 제외하고 막대 그래프 만들기

top10 <- frequency %>%
  filter(word != "국민") %>%
  group_by(president) %>%
  slice_max(n, n = 10, with_ties = F)

ggplot(top10, aes(x = reorder(word, n),
                  y = n,
                  fill = president)) +
  geom_col() +
  coord_flip() +
  facet_wrap(~ president, scales = "free_y")

박근혜 전 대통령 "국민" 빈도 너무 높아 다른 단어들 차이 드러나지 않음, 때문에 전반적인 단어 빈도가 잘 드러나도록 제거