#r #nlp #n-gram
#r #nlp #n-грамм
Вопрос:
Я пытаюсь выяснить, как идентифицировать униграммы и биграммы в тексте на R, а затем сохранить оба в окончательном выводе на основе порогового значения. Я сделал это на Python с помощью модели Phraser от gensim, но не понял, как это сделать в R.
Например:
strings <- data.frame(text = 'This is a great movie from yesterday', 'I went to the movies', 'Great movie time at the theater', 'I went to the theater yesterday')
#Pseudocode below
bigs <- tokenize_uni_bi(strings, n = 1:2, threshold = 2)
print(bigs)
[['this', 'great_movie', 'yesterday'], ['went', 'movies'], ['great_movie', 'theater'], ['went', 'theater', 'yesterday']]
Спасибо!
Ответ №1:
Вы могли бы использовать для этого фреймворк quanteda:
library(quanteda)
# tokenize, tolower, remove stopwords and create ngrams
my_toks <- tokens(strings$text)
my_toks <- tokens_tolower(my_toks)
my_toks <- tokens_remove(my_toks, stopwords("english"))
bigs <- tokens_ngrams(my_toks, n = 1:2)
# turn into document feature matrix and filter on minimum frequency of 2 and more
my_dfm <- dfm(bigs)
dfm_trim(my_dfm, min_termfreq = 2)
Document-feature matrix of: 4 documents, 6 features (50.0% sparse).
features
docs great movie yesterday great_movie went theater
text1 1 1 1 1 0 0
text2 0 0 0 0 1 0
text3 1 1 0 1 0 1
text4 0 0 1 0 1 1
# use convert function to turn this into a data.frame
В качестве альтернативы вы могли бы использовать tidytext package, tm, токенизаторы и т.д. И т.п. Все это немного зависит от результата, который вы ожидаете.
Пример использования tidytext / dplyr выглядит следующим образом:
library(tidytext)
library(dplyr)
strings %>%
unnest_ngrams(bigs, text, n = 2, n_min = 1, ngram_delim = "_", stopwords = stopwords::stopwords()) %>%
count(bigs) %>%
filter(n >= 2)
bigs n
1 great 2
2 great_movie 2
3 movie 2
4 theater 2
5 went 2
6 yesterday 2
Как в quanteda, так и в tidytext доступно множество интерактивных справочных материалов. Смотрите виньетки с обоими пакетами на cran.
Комментарии:
1. Спасибо @phiver! Второй ответ — это именно то, что я искал — следовало поискать повнимательнее в документации tidytext.
2. Просто сноска к этому очень хорошему ответу:
quanteda
также поддерживает / реэкспортирует%>%
, поэтомуdplyr
возможны цепочки в стиле.