如何使用我自己的词典词典分析R中的句子?

时间:2018-07-13 00:15:10

标签: r

我已经形成了一个新的词典词典来分析R中的句子情感。在使用R之前我已经使用过词典词典,但是我不确定如何使用自己的词典。我设法创建了正面和负面的单词列表,该列表计算正面和负面单词的数量,然后提供一个总和。如下例所示,这并未考虑分配给每个单词的分数。

我想分析说这句话“我很高兴,有点伤心”。单词和分数列表示例(列表会比这个更大):

happy, 1.3455
sad, -1.0552

我想将这些单词与句子匹配,并获得总分1.3455 + -1.0552,在这种情况下,总分为0.2903。

如上例中所强调的那样,在分析R中每个句子的情感时,我将如何使用每个单词的实际分数来提供总体分数?

非常感谢, 詹姆斯

1 个答案:

答案 0 :(得分:1)

您可以从宏伟的tidytext包开始:

library(tidytext)
library(tidyverse)

首先,您要分析的数据和一个小的转换:

# data
df <-data_frame(text = c('I am happy and kind of sad','sad is sad, happy is good'))

# add and ID
df <- tibble::rowid_to_column(df, "ID")

# add the name of the ID column
colnames(df)[1] <- "line"

> df
# A tibble: 1 x 2
   line text                      
  <int> <chr>                     
1     1 I am happy and kind of sad

然后,您可以让他们在栏中输入单词。这是一个应用于每个句子(每个ID)的“循环”:

 tidy <- df %>% unnest_tokens(word, text)
    > tidy
# A tibble: 7 x 2
   line word 
  <int> <chr>
1     1 i    
2     1 am   
3     1 happy
4     1 and  
5     1 kind 
6     1 of   
7     1 sad  

现在使用全新的词典:

lexicon <- data_frame(word =c('happy','sad'),scores=c(1.3455,-1.0552))
> lexicon
# A tibble: 2 x 2
  word  scores
  <chr>  <dbl>
1 happy   1.35
2 sad    -1.06

最后,您可以merge词典和数据来获得分数的总和。

merged <- merge(tidy,lexicon, by = 'word')    


现在,对于每个短语,情绪:

scoredf <- aggregate(cbind(scores) ~line, data = merged, sum)
>scoredf
  line  scores
1    1  0.2903
2    2 -0.7649


最后,您可以merge带有分数的初始df,以将短语和分数组合在一起:

scoredf <- aggregate(cbind(scores) ~line, data = merged, sum)
merge(df,scoredf, by ='line')
  line                       text  scores
1    1 I am happy and kind of sad  0.2903
2    2  sad is sad, happy is good -0.7649

如果您想要多个短语,则总体情感得分。
希望对您有帮助!