首页 文章

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

提问于
浏览
0

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

我想分析说这句话“我很开心,有点伤心” . 单词和分数的示例列表(列表将大于此):

happy, 1.3455
sad, -1.0552

我想将这些单词与句子相匹配,并取得分数之和,1.3455 -1.0552,在这种情况下总得分为0.2903 .

如上例所强调的那样,在分析R中每个句子的情绪时,如何获取每个单词的实际分数以提供总分?

非常感谢,詹姆斯

1 回答

  • 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
    

    如果你想要多个短语,整体情绪得分 .
    希望能帮助到你!

相关问题