将情感附加到数据框中的每个单词

时间:2018-10-13 14:14:20

标签: python pandas dataframe sentiment-analysis

我对推文进行了情感分析,但是现在我必须将情感附加到推文中的每个单词。我的情感分析是基于词典中出现的单词总数。我希望这个例子能对您有所帮助。

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

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

1 个答案:

答案 0 :(得分: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)]