【问题标题】:R Stringr, how to replace part of a string, which varies in length?R Stringr,如何替换长度不同的字符串的一部分?
【发布时间】:2020-04-26 09:40:10
【问题描述】:

我正在尝试对一些推文进行情感分析,我需要使用词典将表情符号代码“翻译”成情感。

数据如下:

ID;tweet
1;Btc y<c4><b1>l<c4><b1>n en y<c3><bc> yes yes
2;Top Cryptos:  BTC 13756.50$ | 11449.53<e2><82><ac> going up
3;8. Galileo'nun d<c3><bc>nya good dedi<c4><9f>i i
4;New arrival! Thanks @afilini <e2><9d><a4> #mastering
5;<e2><ad><90><ef><b8><8f><e2><ad><90><ef>

词典如下所示:

ID;emoji;emotion
1;<c4><b1>;glad
2;<c3><bc>;angry
3;<e2><82><ac>;thrilled
4;<c4><9f>;cry
5;<e2><9d><a4>;suspecious
6;<e2><ad><90><ef><b8>;happy
7;<8f><e2>;no
8;<ad><90><ef>;funny

是否可以使用词典将表情符号代码替换为情感?

【问题讨论】:

    标签: r token sentiment-analysis stringr


    【解决方案1】:

    您可以选择使用mgsub 包中的mgsub() 函数,然后通过dplyr::mutate() 添加新列,如下所示。

    df <- data.frame(tweet = c("Btc y<c4><b1>l<c4><b1>n en y<c3><bc> yes yes", 
                               "Top Cryptos:  BTC 13756.50$  11449.53<e2><82><ac> going up"))
    lexicon <- data.frame(emoji = c("<c4><b1>", "<c3><bc>", 
                                    "<e2><82><ac>"), 
                          emotion = c("glad", "angry", "thrilled"))
    

    成为您的推文和词典数据。

    然后一行

    df2 <- df %>% mutate(new = mgsub::mgsub(., lexicon$emoji, lexicon$emotion))
    

    有想要的

    输出

    > df2
                                                           tweet                                                  tweet
    1               Btc y<c4><b1>l<c4><b1>n en y<c3><bc> yes yes                      Btc ygladlgladn en yangry yes yes
    2 Top Cryptos:  BTC 13756.50$  11449.53<e2><82><ac> going up Top Cryptos:  BTC 13756.50$  11449.53thrilled going up
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-14
      • 1970-01-01
      • 1970-01-01
      • 2020-07-28
      • 1970-01-01
      • 2016-09-23
      • 1970-01-01
      • 2022-01-02
      相关资源
      最近更新 更多