我有一个包含大约 50 行句子的 csv 文件。我正在使用 textblob 情绪分析工具。为了测试句子的极性,示例显示您写了一个句子,并显示了极性和主观性。但是,它只适用于单个句子,我希望它适用于我拥有的 csv 文件,因为我不能放入每一行并单独测试它们,因为这会花费太长时间。我该怎么做呢?
TextBlob 显示这个例子,当我输入一个句子时,极性显示,你不能一次输入两个句子,它不允许你。我如何将我的 csv 文件输入到下面的示例中,以便为我提供所有行的极性?
>>> testimonial = TextBlob("Textblob is amazingly simple to use. What great fun!")
>>> testimonial.sentiment
Sentiment(polarity=0.39166666666666666, subjectivity=0.4357142857142857)
>>> testimonial.sentiment.polarity
0.39166666666666666
编辑了 chishaku 解决方案,它对我有用。解决方案:
import csv
from textblob import TextBlob
infile = 'xxx.csv'
with open(infile, 'r') as csvfile:
rows = csv.reader(csvfile)
for row in rows:
sentence = row[0]
blob = TextBlob(sentence)
print blob.sentiment
请您参考如下方法:
在处理 CSV 时,我真的很喜欢 pandas,尽管这对于您想要实现的目标来说过于通用。但也许您想要对数据进行更多处理,所以我发布了 pandas 解决方案。
import pandas as pd
# To read a CSV file
# df = pd.read_csv('sentences.csv')
df = pd.DataFrame({'sentence': ['I am very happy', 'I am very sad', 'I am sad but I am happy too']})
from textblob import TextBlob
# The x in the lambda function is a row (because I set axis=1)
# Apply iterates the function accross the dataframe's rows
df['polarity'] = df.apply(lambda x: TextBlob(x['sentence']).sentiment.polarity, axis=1)
df['subjectivity'] = df.apply(lambda x: TextBlob(x['sentence']).sentiment.subjectivity, axis=1)
>>> print(df)
sentence polarity subjectivity
0 I am very happy 1.00 1
1 I am very sad -0.65 1
2 I am sad but I am happy too 0.15 1
