分词与停用词移除
将文本拆分为词元,并使用 anti_join() 过滤无信息词语
分词与停用词移除 是 CoddyKit 上的免费 R Academy 课时。 这是第 1 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 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 内置了一个 stop_words tibble,其中包含来自三个词典的 1,149 个常见英语停用词:SMART、Snowball 和 onix。这些词(“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))自定义停用词
特定领域的语料库中通常包含一些高频但无关的词(例如医学记录中的“患者”“医生”)。您可以创建自定义停用词 tibble,并使用 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是一个内置 tibble,包含来自 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 Academy 课程的其余内容,请升级到 CoddyKit PRO。 R Academy 课程共包含 4 节课。
「分词与停用词移除」这节课中我会学到什么?
将文本拆分为词元,并使用 anti_join() 过滤无信息词语 你通过在浏览器中直接运行的动手代码来练习 R Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 R Academy 需要有经验吗?
无需任何先前经验。CoddyKit 上的 R Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 1 节课,共 4 节。
「分词与停用词移除」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 R Academy 课中编写并运行代码吗?
能。每节 R Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。