我在CSV
文件上使用情感分析,输出打印出句子的极性和主观性。如何以表格形式获得输出以及句子的分类为正或负或中性添加到它?
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
提前致谢。
答案 0 :(得分:1)
我建议创建一个列表列表并将其导入到pandas数据帧中以获取表结构
j
这将为您提供一个名为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
添加后,您可以创建如下自定义计算:
df = pd.DataFrame(bloblist, columns = ['sentence','sentiment','polarity'])