как получить оценку настроения (и сохранить слова настроения) в кванте? - PullRequest
1 голос
/ 27 мая 2020

Рассмотрим этот простой пример

library(tibble)
library(quanteda)

tibble(mytext = c('this is a good movie',
                  'oh man this is really bad',
                  'quanteda is great!'))

# A tibble: 3 x 1
  mytext                   
  <chr>                    
1 this is a good movie     
2 oh man this is really bad
3 quanteda is great!   

Я хотел бы провести базовый c анализ настроений, но с изюминкой. Вот мой словарь, хранящийся в обычном tibble

mydictionary <- tibble(sentiment = c('positive', 'positive','negative'),
                       word = c('good', 'great', 'bad'))

# A tibble: 3 x 2
  sentiment word 
  <chr>     <chr>
1 positive  good 
2 positive  great
3 negative  bad  

По сути, я хотел бы подсчитать, сколько положительных и отрицательных слов обнаружено в каждом предложении, но также отслеживать совпадающие слова. Другими словами, результат должен выглядеть как

                          mytext nb.pos nb.neg   pos.words
1 this is a good and great movie      2      0 good, great
2      oh man this is really bad      0      1         bad
3             quanteda is great!      1      0       great

Как я могу сделать это в quanteda? Это возможно? Спасибо!

1 Ответ

2 голосов
/ 27 мая 2020

Следите за обновлениями quanteda v. 2.1, в котором мы значительно расширили специализированные функции для анализа настроений. А пока смотрите ниже. Обратите внимание, что я внес некоторые изменения, поскольку есть несоответствие в том, что вы сообщаете как текст и ваш вводимый текст, а также у вас есть все слова настроения в pos.words, а не только положительные слова. Ниже я вычисляю как положительные, так и все совпадения настроений.

# note the amended input text
mytext <- c(
  "this is a good and great movie",
  "oh man this is really bad",
  "quanteda is great!"
)

mydictionary <- tibble::tibble(
  sentiment = c("positive", "positive", "negative"),
  word = c("good", "great", "bad")
)

library("quanteda", warn.conflicts = FALSE)
## Package version: 2.0.9000
## Parallel computing: 2 of 8 threads used.
## See https://quanteda.io for tutorials and examples.

# make the dictionary into a quanteda dictionary
qdict <- as.dictionary(mydictionary)

Теперь мы можем использовать функции поиска, чтобы добраться до вашего окончательного data.frame.

# get the sentiment scores
toks <- tokens(mytext)
df <- toks %>%
  tokens_lookup(dictionary = qdict) %>%
  dfm() %>%
  convert(to = "data.frame")
names(df)[2:3] <- c("nb.neg", "nb.pos")

# get the matches for pos and all words
poswords <- tokens_keep(toks, qdict["positive"])
allwords <- tokens_keep(toks, qdict)

data.frame(
  mytext = mytext,
  df[, 2:3],
  pos.words = sapply(poswords, paste, collapse = ", "),
  all.words = sapply(allwords, paste, collapse = ", "),
  row.names = NULL
)
##                           mytext nb.neg nb.pos   pos.words   all.words
## 1 this is a good and great movie      0      2 good, great good, great
## 2      oh man this is really bad      1      0                     bad
## 3             quanteda is great!      0      1       great       great
...