토큰화와 불용어 제거
텍스트를 토큰으로 나누고 anti_join()으로 정보성이 낮은 단어를 걸러냅니다.
토큰화와 불용어 제거은(는) CoddyKit의 무료 R Academy 강의입니다. 이것은 4개 중 1번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 R Academy 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. R Academy 강의에는 총 4개의 강의가 포함되어 있습니다.
텍스트 마이닝이란?
텍스트 마이닝(또는 텍스트 분석)은 구조화되지 않은 텍스트를 통계적으로 분석할 수 있는 구조화된 데이터로 변환합니다. tidytext 패키지는 정돈된 방식의 분석을 지원합니다. 각 행이 하나의 토큰(단어, 바이그램, 문장)이 되므로 dplyr 및 ggplot2와 호환됩니다.
library(tidytext)
library(dplyr)
# A simple text corpus
text_df <- tibble::tibble(
doc_id = 1:3,
text = c(
'The quick brown fox jumps over the lazy dog.',
'Text mining with R is powerful and fun.',
'Natural language processing enables many applications.'
)
)
cat('Input: ', nrow(text_df), 'documents\n')
cat('Columns:', names(text_df), '\n')unnest_tokens: 단어 토큰화
unnest_tokens(output, input)은 텍스트를 토큰 하나당 한 행인 형식으로 나눕니다. 기본적으로 단어 단위로 토큰화하며, 소문자로 변환하고 문장 부호를 제거합니다. token 인수는 'words', 'ngrams', 'sentences' 등을 지원합니다.
library(tidytext)
library(dplyr)
text_df <- tibble::tibble(
doc_id = 1:2,
text = c(
'R is a great language for data analysis.',
'Text mining reveals hidden patterns in documents.'
)
)
# Tokenise into words
tokens <- text_df |>
unnest_tokens(word, text)
cat('Tokens extracted:', nrow(tokens), '\n')
print(tokens)stop_words 데이터 세트
tidytext에는 SMART, Snowball, onix라는 세 어휘 목록에서 가져온 영어 불용어 1,149개가 포함된 내장 stop_words 티블이 들어 있습니다. 이러한 단어("the", "is", "and" 등)는 의미 정보가 거의 없으므로 일반적으로 분석 전에 제거합니다.
library(tidytext)
library(dplyr)
# Inspect the stop_words dataset
cat('Total stop words:', nrow(stop_words), '\n')
cat('Lexicons:', paste(unique(stop_words$lexicon), collapse = ', '), '\n')
# First few stop words from each lexicon
stop_words |>
group_by(lexicon) |>
slice_head(n = 3) |>
print()anti_join: 불용어 제거
anti_join(tokens, stop_words, by = 'word')는 word가 stop_words의 항목과 일치하는 모든 행을 제거합니다. 이는 불용어를 제거할 때 사용하는 표준 tidytext 패턴으로, 깔끔하고 읽기 쉬우며 쉽게 확장할 수 있습니다.
library(tidytext)
library(dplyr)
text_df <- tibble::tibble(
doc_id = 1:3,
text = c(
'The quick brown fox jumps over the lazy dog',
'A stitch in time saves nine important words',
'To be or not to be that is the question'
)
)
tokens <- text_df |>
unnest_tokens(word, text)
cat('Before removing stop words:', nrow(tokens), '\n')
tokens_clean <- tokens |>
anti_join(stop_words, by = 'word')
cat('After removing stop words:', nrow(tokens_clean), '\n')
print(tokens_clean)count: 단어 빈도
토큰화하고 불용어를 제거한 뒤 count(word, sort = TRUE)를 사용해 단어 빈도를 계산합니다. 이는 다양한 텍스트 마이닝 분석의 기초입니다. 의미 있는 단어 중 가장 자주 등장하는 단어가 문서의 주제를 드러냅니다.
library(tidytext)
library(dplyr)
# Use Jane Austen's novels from janeaustenr package
# For demo: simulate a small corpus
corpus <- tibble::tibble(
text = c(
'data science involves statistics programming analysis',
'machine learning algorithms data patterns training',
'statistics probability distributions random variables data',
'programming languages python r julia statistics',
'analysis patterns distributions algorithms science'
)
)
word_counts <- corpus |>
unnest_tokens(word, text) |>
anti_join(stop_words, by = 'word') |>
count(word, sort = TRUE)
cat('Top 8 words:\n')
print(head(word_counts, 8))사용자 지정 불용어
특정 분야의 말뭉치에는 관련성이 낮지만 높은 빈도로 나타나는 단어가 포함되는 경우가 많습니다(예: 의료 기록의 "patient", "doctor"). 사용자 지정 불용어 티블을 만들고 bind_rows()를 사용해 내장 어휘 목록에 결합합니다.
library(tidytext)
library(dplyr)
# Domain-specific words to remove
custom_stops <- tibble::tibble(
word = c('data', 'analysis', 'r', 'using', 'also'),
lexicon = 'custom'
)
# Combine with built-in stop words
all_stops <- bind_rows(stop_words, custom_stops)
cat('Total stop words after custom:', nrow(all_stops), '\n')
corpus <- tibble::tibble(
text = c(
'Using R for data analysis and machine learning models',
'Statistical data analysis also involves data visualisation'
)
)
clean_tokens <- corpus |>
unnest_tokens(word, text) |>
anti_join(all_stops, by = 'word') |>
count(word, sort = TRUE)
print(clean_tokens)바이그램 토큰화
token = 'ngrams', n = 2로 설정하면 연속된 두 단어 쌍(바이그램)으로 토큰화합니다. 바이그램은 개별 단어만으로는 파악하기 어려운 "machine learning"이나 "data science" 같은 구문을 포착하여 더 풍부한 맥락을 제공합니다.
library(tidytext)
library(dplyr)
corpus <- tibble::tibble(
doc_id = 1:2,
text = c(
'machine learning and deep learning are powerful techniques',
'natural language processing uses machine learning methods'
)
)
bigrams <- corpus |>
unnest_tokens(bigram, text, token = 'ngrams', n = 2)
cat('Bigrams extracted:', nrow(bigrams), '\n')
print(bigrams)
# Count most common bigrams
bigram_counts <- bigrams |> count(bigram, sort = TRUE)
cat('\nTop bigrams:\n')
print(head(bigram_counts, 5))바이그램 품질 필터링
빈도가 높은 바이그램에는 "of the"와 같은 불용어 조합이 많이 포함됩니다. tidyr::separate()로 바이그램을 두 열로 나누고, 둘 중 하나라도 불용어인 행을 필터링한 다음 다시 결합하여 의미 있는 구문 쌍을 얻습니다.
library(tidytext)
library(dplyr)
library(tidyr)
corpus <- tibble::tibble(
text = c(
'the field of machine learning and deep learning is growing',
'natural language processing is a subfield of artificial intelligence'
)
)
bigrams_filtered <- corpus |>
unnest_tokens(bigram, text, token = 'ngrams', n = 2) |>
separate(bigram, into = c('word1', 'word2'), sep = ' ') |>
filter(
!word1 %in% stop_words$word,
!word2 %in% stop_words$word
) |>
unite(bigram, word1, word2, sep = ' ') |>
count(bigram, sort = TRUE)
print(bigrams_filtered)단어 빈도 시각화
ggplot2를 사용해 단어 빈도를 막대 차트로 그립니다. reorder(word, n)으로 막대를 정렬하고, coord_flip()으로 가로 방향 레이블을 사용합니다. 이는 텍스트 마이닝에서 정보를 가장 효과적으로 전달하는 결과 중 하나입니다.
library(tidytext)
library(dplyr)
library(ggplot2)
corpus <- tibble::tibble(
text = c(
'statistics probability machine learning algorithms patterns',
'data science programming analysis visualisation models',
'machine learning deep learning neural networks patterns',
'probability statistics hypothesis testing distributions',
'algorithms optimisation gradient descent models training'
)
)
top_words <- corpus |>
unnest_tokens(word, text) |>
anti_join(stop_words, by = 'word') |>
count(word, sort = TRUE) |>
slice_head(n = 10)
ggplot(top_words, aes(reorder(word, n), n)) +
geom_col(fill = 'steelblue') +
coord_flip() +
labs(x = 'Word', y = 'Count', title = 'Top 10 Terms') +
theme_minimal()문서별 단어 개수
말뭉치에 여러 문서가 있다면 문서 식별자 열을 추가하고 doc_id, word로 그룹화하여 문서별 단어 빈도를 계산합니다. 이렇게 계산한 결과는 TF-IDF 및 주제 모형 분석에 바로 사용할 수 있습니다.
library(tidytext)
library(dplyr)
docs <- tibble::tibble(
doc_id = c(1, 1, 1, 2, 2, 2, 3, 3, 3),
text = c(
'machine learning models training',
'neural networks deep learning',
'algorithms gradient descent optimisation',
'statistical analysis probability distributions',
'hypothesis testing confidence intervals regression',
'bayesian inference prior posterior likelihood',
'data visualisation plots charts dashboards',
'ggplot2 ggvis plotly interactive graphics',
'colour scales aesthetics themes layers'
)
)
word_counts <- docs |>
unnest_tokens(word, text) |>
anti_join(stop_words, by = 'word') |>
count(doc_id, word, sort = TRUE)
cat('Word-doc pairs:', nrow(word_counts), '\n')
print(head(word_counts, 10))문장 토큰화
token = 'sentences'로 설정하면 문장 경계에서 텍스트를 나눕니다. 문장 단위 토큰은 감정 분석(각 문장에 점수 부여), 요약(대표 문장 선택), 질의응답 작업에 유용합니다.
library(tidytext)
library(dplyr)
doc <- tibble::tibble(
id = 1L,
text = paste(
'R is a statistical programming language.',
'It is widely used in data science and machine learning.',
'The tidyverse makes data manipulation easy.',
'Text mining with tidytext is elegant and powerful.'
)
)
sentences <- doc |>
unnest_tokens(sentence, text, token = 'sentences')
cat('Sentences found:', nrow(sentences), '\n')
print(sentences$sentence)빠른 확인
unnest_tokens()를 사용해 말뭉치를 단어로 토큰화했으며, 흔한 영어 단어를 제거하려고 합니다. 내장 stop_words 데이터 세트를 사용해 이를 수행하는 연산은 무엇일까요?
복습: 토큰화와 불용어
핵심 내용:
unnest_tokens(word, text)는 원시 텍스트를 단어 하나당 한 행인 정돈된 형식으로 변환합니다- 기본 동작은 소문자 변환과 문장 부호 제거이며,
'words','ngrams','sentences'를 지원합니다 stop_words는 3개 어휘 목록에서 가져온 흔한 영어 단어 1,149개가 들어 있는 내장 티블입니다anti_join(tokens, stop_words, by = 'word')는 불용어를 제거합니다bind_rows()와 결합하면 특정 분야의 사용자 지정 불용어를 추가할 수 있습니다count(word, sort = TRUE)는 정돈된 토큰에서 단어 빈도를 계산합니다- 바이그램:
unnest_tokens(bigram, text, token = 'ngrams', n = 2)
library(tidytext)
library(dplyr)
tibble::tibble(text = 'The quick brown fox jumps over the lazy dog') |>
unnest_tokens(word, text) |>
anti_join(stop_words, by = 'word') |>
count(word, sort = TRUE) |>
print()AI 튜터와 함께 R을(를) 배우세요 — 무료
브라우저에서 실제 코드를 작성하고 실행하며, 24/7 AI 튜터로부터 즉각적인 도움을 받고, 웹이나 앱에서 중단한 부분부터 계속 학습하세요.
- 코스
- 43
- 레슨
- 159
자주 묻는 질문
“토큰화와 불용어 제거” 강의는 무료인가요?
네 — “토큰화와 불용어 제거” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 R Academy 강의 전체를 잠금 해제할 수 있습니다. R Academy 강의에는 총 4개의 강의가 포함되어 있습니다.
“토큰화와 불용어 제거”에서 뭘 배우나요?
텍스트를 토큰으로 나누고 anti_join()으로 정보성이 낮은 단어를 걸러냅니다. 브라우저에서 직접 실행하는 실습 코드로 R Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
R Academy을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 R Academy은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 1번째 강의입니다.
“토큰화와 불용어 제거” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 R Academy 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 R Academy 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- 토큰화와 불용어 제거
- TF-IDF와 단어 빈도 분석
- R에서 감성 분석
- LDA를 활용한 토픽 모델링