【问题标题】:How to split every sentence into individual words and average polarity score per sentence and append into new column in dataframe?如何将每个句子拆分为单个单词和每个句子的平均极性分数并附加到数据框中的新列中?
【发布时间】:2018-08-28 01:10:33
【问题描述】:

我可以成功地将一个句子拆分为单个单词,并使用此代码对每个单词的极性得分进行平均。它工作得很好。

import statistics as s
from textblob import TextBlob

a = TextBlob("""Thanks, I'll have a read!""")
print(a)

    c=[]
    for i in a.words: 
        c.append(a.sentiment.polarity)
        d = s.mean(c)


d = 0.25
a.words = WordList(['Thanks', 'I', "'ll", 'have', 'a', 'read'])

如何将上述代码转移到如下所示的 df 中?:

df

     text
1    Thanks, I’ll have a read!

但是取每个单词每个极性的平均值?

壁橱是我可以对 df 中的每个句子的每个句子应用极性:

def sentiment_calc(text):
    try:
        return TextBlob(text).sentiment.polarity
    except:
        return None

df_sentences['sentiment'] = df_sentences['text'].apply(sentiment_calc)

【问题讨论】:

  • 您想要对您的DataFrame 中的每个TextBlob 进行极性分析吗?
  • 我想要数据框中句子中每个单词极性的平均值
  • 单词没有polarity;只有TextBlobs 这样做
  • @aydow 感谢您的更正。我在上面的代码中添加了一些变量。
  • 您的代码无法正常工作(导入 Textblob 失败,缩进被破坏)。帮助你会更容易

标签: python pandas dataframe nlp textblob


【解决方案1】:

我的印象是情绪极性只适用于 TextBlob 类型。

所以我的想法是将文本 blob 拆分为单词(使用拆分功能 -- 参见 doc here)并将它们转换为 TextBlob 对象。 这是在列表理解中完成的:

[TextBlob(x).sentiment.polarity for x in a.split()]

所以整个事情看起来像这样:

import statistics as s
from textblob import TextBlob
import pandas as pd

a = TextBlob("""Thanks, I'll have a read!""")

def compute_mean(a):
    return s.mean([TextBlob(x).sentiment.polarity for x in a.split()])

print(compute_mean("Thanks, I'll have a read!"))

df = pd.DataFrame({'text':["Thanks, I'll have a read!",
    "Second sentence",
    "a bag of apples"]})

df['score'] = df['text'].map(compute_mean)
print(df)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-03-13
    • 2019-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-17
    相关资源
    最近更新 更多