使用 Python 和 TextBlob 为情绪分析设置 n 元语法



我想用PythonTextBlob库对一些句子进行情感分析。 我知道如何使用它,但是有没有办法n-grams设置它? 基本上,我不想逐字分析,但我想分析2个词,3个词,因为短语可以承载更多的含义和情感。

例如,这就是我所做的(它有效(:

from textblob import TextBlob
my_string = "This product is very good, you should try it"
my_string = TextBlob(my_string)
sentiment = my_string.sentiment.polarity
subjectivity = my_string.sentiment.subjectivity
print(sentiment)
print(subjectivity)

但是我该如何申请,例如 n-gram = 2,n-gram = 3 等? 是否可以使用TextBlobVaderSentimentlib 来做到这一点?

这是一个在不使用任何库的情况下查找 n 元语法的解决方案。

from textblob import TextBlob
def find_ngrams(n, input_sequence):
# Split sentence into tokens.
tokens = input_sequence.split()
ngrams = []
for i in range(len(tokens) - n + 1):
# Take n consecutive tokens in array.
ngram = tokens[i:i+n]
# Concatenate array items into string.
ngram = ' '.join(ngram)
ngrams.append(ngram)
return ngrams
if __name__ == '__main__':
my_string = "This product is very good, you should try it"
ngrams = find_ngrams(3, my_string)
analysis = {}
for ngram in ngrams:
blob = TextBlob(ngram)
print('Ngram: {}'.format(ngram))
print('Polarity: {}'.format(blob.sentiment.polarity))
print('Subjectivity: {}'.format(blob.sentiment.subjectivity))

要更改 ngram 长度,请更改函数find_ngrams()中的n值。

textblob 中没有参数来定义 n 元语法,而不是用作情感分析特征的单词/单元语法。

Textblob 使用极性词典来计算文本的整体情绪。该词典包含 unigram,这意味着它只能为您提供单词的情感,而不能为您提供带有 n>1 的 n-gram。

我想你可以通过将双元语法或三元语法输入情感分类器来解决这个问题,就像你输入一个句子,然后创建一个包含累积情绪值的 n 元语法字典一样。 但我不确定这是个好主意。我假设您正在寻找双元词来解决否定("不错"(等问题,并且词典方法将无法用于将情绪值翻转为

Textblob 还包含一个使用朴素贝叶斯分类器而不是词典方法的选项。这是在 nltk 提供的电影评论语料库上训练的,但训练的默认功能是单词/unigram,据我所知,从偷看源代码中可以看出。 您也许可以在其中实现自己的特征提取器来提取 n 元语法而不是单词,然后相应地重新训练它并用于您的数据。

无论如何,我建议您使用unigram和n>1-gram的组合作为功能,因为完全删除unigram可能会对您的性能产生负面影响。双元图的分布要稀疏得多,因此在训练时会遇到数据稀疏性问题。

最新更新