【问题标题】:Sentiment analysis on a csv file using textblob使用 textblob 对 csv 文件进行情感分析
【发布时间】:2018-06-25 12:28:39
【问题描述】:

我对@9​​87654321@ 文件进行了情感分析,输出打印了一个句子的极性和主观性。如何获得表格格式的输出以及添加的句子分类为正面或负面或中性?

    import csv
    from textblob import TextBlob

    infile = 'sentence.csv'

    with open(infile, 'r') as csvfile:
        rows = csv.reader(csvfile)
    for row in rows:
        sentence = row[0]
        blob = TextBlob(sentence)
        print (sentence)
        print (blob.sentiment.polarity, blob.sentiment.subjectivity)

我的代码的输出是:

    i am very happy
    1.0 1.0
    its very sad
    -0.65 1.0
    they are bad
    -0.6999999999999998 0.6666666666666666
    hate the life
    -0.8 0.9
    she is so fantastic
    0.4 0.9

提前致谢。

【问题讨论】:

  • 您熟悉pandas 数据帧吗?
  • 我是初学者但我能理解
  • @Usernamenotfound 我尝试使用 pandas 但我无法为 csv 文件执行此操作。我可以为单个句子做到这一点。谢谢

标签: python csv sentiment-analysis textblob


【解决方案1】:

我建议创建一个列表列表并将其导入 pandas 数据框以获取表结构

import csv
from textblob import TextBlob
import pandas as pd
import numpy as np

infile = 'sentence.csv'
bloblist = list()

with open(infile, 'r') as csvfile:
    rows = csv.reader(csvfile)

for row in rows:
    sentence = row[0]
    blob = TextBlob(sentence)
    bloblist.append((sentence,blob.sentiment.polarity, blob.sentiment.subjectivity))

这将为您提供一个名为 bloblist 的列表列表,将其转换为类似的 pandas 数据框

df = pd.DataFrame(bloblist, columns = ['sentence','sentiment','polarity'])

添加后,您可以像这样创建自定义计算:

df['positive'] = np.where(df.sentiment > .5,1,0)

【讨论】:

  • 一定会的
猜你喜欢
  • 1970-01-01
  • 2016-06-04
  • 1970-01-01
  • 2022-06-22
  • 2020-03-26
  • 2017-10-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多