【问题标题】:How to label text either positive or negative based on words in a dictionary in R?如何根据R中字典中的单词标记文本是正面的还是负面的?
【发布时间】:2021-01-07 16:55:13
【问题描述】:

假设我有一个包含 cmets 的向量(数据框)(每一行是不同的注释):

comment
'well done!'
'terrible work'
'quit your job'
'hi'

我有以下数据框,其中包含 positivenegative 单词(即字典)

positive negative
well     terrible
done     quit

R 中是否有一种方法可以使用此字典来标记第一个数据帧中的 cmets positivenegativeneutral,具体取决于它们是否包含更多或更少的正/负 cmets?

即我希望输出是一个看起来像这样的数据框:

comment          label
'well done!'     positive
'terrible work'  negative
'quit your job'  negative
'hi'             neutral

有谁知道如何在 R 中做到这一点?

【问题讨论】:

    标签: r sentiment-analysis


    【解决方案1】:

    这行得通吗:

    library(dplyr)
    library(stringr)
    comm %>% mutate(label = case_when(str_detect(comments, str_c(dict$positive, collapse = '|')) ~ 'positive',
                                       str_detect(comments, str_c(dict$negative, collapse = '|')) ~ 'negative',
                                       TRUE ~ 'neutral'))
           comments    label
    1    well done! positive
    2 terrible work negative
    3 quit your job negative
    4            hi  neutral
    

    根据 OP 的要求:

    comm %>% mutate(p_count = str_count(comments, str_c(dict$positive, collapse = '|')), 
                     n_count = str_count(comments, str_c(dict$negative, collapse = '|'))) %>% 
               mutate(label = case_when(p_count > n_count ~ 'positive',
                                        p_count < n_count ~ 'negative',
                                        TRUE ~ 'neutral')) %>% select(comments, label)
                     comments    label
    1              well done! positive
    2      terrible well work  neutral
    3 quit your job well well positive
    4                      hi  neutral
    5      terrible quit well negative
    

    使用的新数据:

    comm
                     comments
    1              well done!
    2      terrible well work
    3 quit your job well well
    4                      hi
    5      terrible quit well
    
    dict
    # A tibble: 2 x 2
      positive negative
      <chr>    <chr>   
    1 well     terrible
    2 done     quit    
    

    【讨论】:

    • 谢谢!两个问题:collapse = '|' 部分是做什么的?这是否考虑了单词的比例?例如,如果评论包含的正面词多于负面词,我希望标签是正面的。如果它包含相同的数量,我希望标签是中性的。
    • 折叠 = '|'类似于 OR,因此 str_detect 会检测此字符串或下一个字符串,依此类推...根据您的新查询,我已经编辑了您的示例数据并更新了我的答案。请检查是否有效。
    猜你喜欢
    • 2011-06-08
    • 2022-01-22
    • 2015-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-26
    • 2012-10-11
    相关资源
    最近更新 更多