如何使用整洁的文本使用双字母和三元组

时间:2017-08-13 18:21:52

标签: r token tidytext

我正在尝试使用tidytext同时使用bigram和trigram。我可以使用什么代码来代替2和3个单词。

这是仅使用bigrams的代码:

library(tidytext)
library(janeaustenr)

austen_bigrams <- austen_books() %>%
  unnest_tokens(bigram, text, token = "ngrams", n = 2)

austen_bigrams

1 个答案:

答案 0 :(得分:6)

如果查看?unnest_tokens,它会告诉您...是否传递给tokenizer的参数。对于ngrams,那是tokenizers::tokenize_ngrams,如果你查看它的帮助页面,它有一个n_min参数,所以你可以这样做

library(magrittr)
library(tidytext)
library(janeaustenr)

austen_bigrams <- austen_books() %>% 
    head(1000) %>%    # otherwise this will get very large
    unnest_tokens(bigram, text, token = "ngrams", n = 3, n_min = 2)

austen_bigrams
#> # A tibble: 19,801 x 2
#>                   book                bigram
#>                 <fctr>                 <chr>
#>  1 Sense & Sensibility             sense and
#>  2 Sense & Sensibility sense and sensibility
#>  3 Sense & Sensibility       and sensibility
#>  4 Sense & Sensibility    and sensibility by
#>  5 Sense & Sensibility        sensibility by
#>  6 Sense & Sensibility   sensibility by jane
#>  7 Sense & Sensibility               by jane
#>  8 Sense & Sensibility        by jane austen
#>  9 Sense & Sensibility           jane austen
#> 10 Sense & Sensibility      jane austen 1811
#> # ... with 19,791 more rows