不清楚运行情绪分析的Google NL API的TypeError消息



目标

对pandas数据帧中的一列文本运行情感分析,让它为每行文本返回分数和幅度值。

当前代码

这就是我正在运行的,拉入一个数据帧(df03(,其中包含我要分析的一列文本(text02(。

# Imports the Google Cloud client library
from google.cloud import language_v1
# Instantiates a client
client = language_v1.LanguageServiceClient()
# The text to analyze
text = df03.loc[:,"text02"]
document = language_v1.Document(
content=text, type_=language_v1.types.Document.Type.PLAIN_TEXT
)
# Detects the sentiment of the text
sentiment = client.analyze_sentiment(
request={"document": document}
).document_sentiment
print("Text: {}".format(text))
print("Sentiment: {}, {}".format(sentiment.score, sentiment.magnitude))

这是返回的错误信息

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-7-1c6f7c607084> in <module>()
8 text = df03.loc[:,"text02"]
9 document = language_v1.Document(
---> 10     content=text, type_=language_v1.types.Document.Type.PLAIN_TEXT
11 )
12 
/usr/local/lib/python3.7/dist-packages/proto/message.py in __init__(self, mapping, ignore_unknown_fields, **kwargs)
562 
563         # Create the internal protocol buffer.
--> 564         super().__setattr__("_pb", self._meta.pb(**params))
565 
566     def _get_pb_type_from_key(self, key):
TypeError: 01                          Max Muncy is great!
02               The worst Dodger is Max muncy.
03   has type Series, but expected one of: bytes, unicode

评估

错误消息指向以下行:

content=text, type_=language_v1.types.Document.Type.PLAIN_TEXT

TypeError消息试图解释发生了什么:

has type Series, but expected one of: bytes, unicode

因此,它似乎识别出了数据帧df03text列下的文本简介列表,但显然我未能建立正确的数据类型设置。

但是,我不确定应该在哪里设置"类型",因为文档中唯一的"文档类型"设置似乎是HTML、PLAIN_TEXT或Type_UNSPECIFIED。其中,我确信PLAIN_TEXT是对的。

文档:https://googleapis.dev/python/language/latest/language_v1/types.html#google.cloud.language_v1.types.Document

因此,这让我不清楚错误消息表明了什么,也不清楚我应该如何进行故障排除。

非常感谢对此提供的任何意见。

doug

看起来Google的API无法直接处理pandas系列,但希望您一次传递一个字符串。尝试将自定义函数apply添加到包含文本的DataFrame列:

def get_sentiment(text):
# The text to analyze
document = language_v1.Document(
content=text,
type_=language_v1.types.Document.Type.PLAIN_TEXT
)
# Detects the sentiment of the text
sentiment = client.analyze_sentiment(
request={"document": document}
).document_sentiment
return sentiment

df03["sentiment"] = df03["text02"].apply(get_sentiment)

最新更新