如何将列表对象作为字符串传递?

2024-09-29 23:26:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我在用Textblob分析一本书的全文,通过单独分析句子来聚合这一章的语气。我有一个脚本,可以将章节转换为单个句子的列表,但是我无法找到一种方法将这些列表对象作为字符串传递给naivebayes分析器,因为它只需要字符串输入。你知道吗

到目前为止,我只尝试传递整个列表作为参数,但它总是给我同样的错误。你知道吗

 TypeError: The `text` argument passed to `__init__(text)` must be a string, 
 not <class 'list'>

这是我的代码:

from textblob import TextBlob
from textblob.sentiments import NaiveBayesAnalyzer
blob = TextBlob("This is a horrible idea.", analyzer=NaiveBayesAnalyzer())
blob.sentiment
print(blob.sentiment)

我的列表如下所示:

sentences = ['Maria was five years old the first time she heard the word 
hello.\n', 'It happened on a Thursday.\n',]

如何修改此代码以接收整个句子列表并将输出作为数据帧传递?如果可能的话,我想要这样的东西:

                                         Line          Polarity Subjectivity Classification
0    Mariam was five years old the first time sh      0.175000   0.266667   Pos                                                 
1    It happened on a Thursday.                       0.000000   0.000000 Neu

Tags: the字符串代码textfromimport列表blob
1条回答
网友
1楼 · 发布于 2024-09-29 23:26:54

你的意思是这样构造一个数据帧吗。至少这是我从你的问题中理解的。 我假设你有一个句子列表,在运行分析程序之前,我把它们连接成一个段落。你知道吗

import pandas as pd
from textblob import TextBlob

from textblob.sentiments import NaiveBayesAnalyzer

df = pd.DataFrame(columns = ['Line','Polarity', 'Subjectivity' ,'Classification'])
sentences = ['Maria was five years old the first time she heard the word hello.\n', 'It happened on a Thursday.\n',]

blob = TextBlob("".join(sentences),analyzer=NaiveBayesAnalyzer())
for sentence in blob.sentences:
    df.loc[len(df)] = [str(sentence),sentence.polarity, sentence.subjectivity,sentence.sentiment.classification]
print(df)

相关问题 更多 >

    热门问题