2

我有一个包含大约 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
4

2 回答 2

6

我真的很喜欢pandas处理 CSV,尽管这对于您想要实现的目标来说太通用了。但也许您想对您的数据进行更多处理,所以我发布了 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
于 2016-02-22T17:04:42.423 回答
4

您需要遍历 csv 文件中的每一行。

首先,打开 csv 文件。

然后对于文件中的每一行,我们可以使用row[0].

import csv
from textblob import TextBlob

infile = '/path/to/file.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
于 2016-02-22T17:01:26.470 回答