整齐的文本格式中的单词替换

Word substitution within tidy text format

您好,我正在使用 tidy_text 格式,我正在尝试将字符串 "emails" 和 "emailing" 替换为 "email"。

set.seed(123)
terms <- c("emails are nice", "emailing is fun", "computer freaks", "broken modem")
df <- data.frame(sentence = sample(terms, 100, replace = TRUE))
df
str(df)
df$sentence <- as.character(df$sentence)
tidy_df <- df %>% 
unnest_tokens(word, sentence)

tidy_df %>% 
count(word, sort = TRUE) %>% 
filter( n > 20) %>% 
mutate(word = reorder(word, n)) %>% 
ggplot(aes(word, n)) +
geom_col() +
xlab(NULL) + 
coord_flip()

这很好用,但是当我使用时:

 tidy_df <- gsub("emailing", "email", tidy_df)

再次替换文字和 运行 条形图,我收到以下错误消息:

使用方法错误("group_by_"): 没有适用于 'group_by_' 的方法应用于 class "character"

的对象

有谁知道如何在不改变 tidy_text 的 structure/class 的情况下轻松替换整洁文本格式中的单词?

像这样删除单词的结尾称为 词干提取,如果您愿意,R 中有几个包可以为您完成这项工作。一个是 hunspell package from rOpenSci,另一个选项是实现波特算法词干提取的 SnowballC 包。你会像这样实现:

library(dplyr)
library(tidytext)
library(SnowballC)

terms <- c("emails are nice", "emailing is fun", "computer freaks", "broken modem")

set.seed(123)
data_frame(txt = sample(terms, 100, replace = TRUE)) %>%
        unnest_tokens(word, txt) %>%
        mutate(word = wordStem(word))
#> # A tibble: 253 × 1
#>      word
#>     <chr>
#> 1   email
#> 2       i
#> 3     fun
#> 4  broken
#> 5   modem
#> 6   email
#> 7       i
#> 8     fun
#> 9  broken
#> 10  modem
#> # ... with 243 more rows

请注意,它正在截断 所有 您的文本,并且有些词看起来不再像真实的词;你可能关心也可能不关心。

如果您不想使用像 SnowballC 或 hunspell 这样的词干分析器来提取所有文本,您可以在 mutate() 中使用 dplyr 的 if_else 来仅替换特定的词。

set.seed(123)
data_frame(txt = sample(terms, 100, replace = TRUE)) %>%
        unnest_tokens(word, txt) %>%
        mutate(word = if_else(word %in% c("emailing", "emails"), "email", word))
#> # A tibble: 253 × 1
#>      word
#>     <chr>
#> 1   email
#> 2      is
#> 3     fun
#> 4  broken
#> 5   modem
#> 6   email
#> 7      is
#> 8     fun
#> 9  broken
#> 10  modem
#> # ... with 243 more rows

或者使用 stringr 包中的 str_replace 可能更有意义。

library(stringr)
set.seed(123)
data_frame(txt = sample(terms, 100, replace = TRUE)) %>%
        unnest_tokens(word, txt) %>%
        mutate(word = str_replace(word, "email(s|ing)", "email"))
#> # A tibble: 253 × 1
#>      word
#>     <chr>
#> 1   email
#> 2      is
#> 3     fun
#> 4  broken
#> 5   modem
#> 6   email
#> 7      is
#> 8     fun
#> 9  broken
#> 10  modem
#> # ... with 243 more rows