Присоединить токены к предложению - PullRequest
1 голос
/ 23 февраля 2020

Я делаю некоторый анализ текста с некоторыми свободными текстовыми данными с tidytext. Рассмотрим примеры предложений:

"The quick brown fox jumps over the lazy dog"
"I love books"

Мой подход с использованием токенов с использованием tidytext:

unigrams = tweet_text %>% 
  unnest_tokens(output = word, input = txt) %>%
  anti_join(stop_words)

Результаты следующие:

The
quick
brown
fox
jumps
over 
the
lazy
dog

Теперь мне нужно присоединиться к каждой униграмме вернуться к исходному предложению:

"The quick brown fox jumps over the lazy dog" | The
"The quick brown fox jumps over the lazy dog" | quick
"The quick brown fox jumps over the lazy dog" | brown
"The quick brown fox jumps over the lazy dog" | fox
"The quick brown fox jumps over the lazy dog" | jumps 
"The quick brown fox jumps over the lazy dog" | over
"The quick brown fox jumps over the lazy dog" | the
"The quick brown fox jumps over the lazy dog" | lazy 
"The quick brown fox jumps over the lazy dog" | dog
"I love books" | I
"I love books" | love
"I love books  | books


Я немного застрял. Решение должно масштабироваться на тысячи предложений. Я думал, что такая функция может быть родной для tidytext, но еще ничего не нашел.

1 Ответ

1 голос
/ 23 февраля 2020

Вы ищете аргумент drop = FALSE:

library(dplyr)
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union
library(tidytext)

tweet_text <- tibble(id = 1:2,
                     text = c("The quick brown fox jumps over the lazy dog",
                              "I love books"))

tweet_text %>% 
  unnest_tokens(output = word, input = text, drop = FALSE)
#> # A tibble: 12 x 3
#>       id text                                        word 
#>    <int> <chr>                                       <chr>
#>  1     1 The quick brown fox jumps over the lazy dog the  
#>  2     1 The quick brown fox jumps over the lazy dog quick
#>  3     1 The quick brown fox jumps over the lazy dog brown
#>  4     1 The quick brown fox jumps over the lazy dog fox  
#>  5     1 The quick brown fox jumps over the lazy dog jumps
#>  6     1 The quick brown fox jumps over the lazy dog over 
#>  7     1 The quick brown fox jumps over the lazy dog the  
#>  8     1 The quick brown fox jumps over the lazy dog lazy 
#>  9     1 The quick brown fox jumps over the lazy dog dog  
#> 10     2 I love books                                i    
#> 11     2 I love books                                love 
#> 12     2 I love books                                books

Создан в 2020-02-22 с помощью пакета Представить (v0.3.0)

...