【问题标题】:Attach sentiment to each word from a dataframe将情绪附加到数据框中的每个单词
【发布时间】:2018-10-13 14:14:20
【问题描述】:

我对推文进行了情绪分析,但现在我必须将情绪附加到推文文本中的每个单词。我的情绪分析是基于字典中出现的单词的总和。我希望这个例子可以帮助到你。

我尝试使用此功能,但在这里不起作用。

def append_sentiment(sentences, sentiment):
return [(word, sentiment) for sentence in sentences
                          for word in sentence.split()]

append_sentiment(df['text'], df['score'])

例子:

id | text | score

12 | I like this | 2

想要的结果:

id | text | score

12 | ('I', 2), ('like', 2), ('this', 2) | 2

【问题讨论】:

    标签: python pandas dataframe sentiment-analysis


    【解决方案1】:

    您可以使用itertools.repeat 轻松构造(word, sentiment) 元组:

    from itertools import repeat
    
    mapped = df.apply(lambda row: list(zip(row.text.split(), repeat(row.score))), axis=1)
    print(mapped)
    0    [(I, 2), (like, 2), (this, 2)]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-20
      • 1970-01-01
      • 2020-09-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多