【发布时间】:2023-03-12 21:33:02
【问题描述】:
我有一个 Pandas 数据框,其中包含我想使用 Google 的 NLP API 分析的许多社交媒体 cmets。 Google 的文档仅讨论(据我所知)如何对单个字符串进行分类,而不是在一个请求中对多个字符串进行分类。对 API 的每个请求,一次对一条评论进行分类,大约需要半秒,当我试图在任何时候对超过 10,000 条评论进行分类时,这非常慢。有没有办法将字符串列表单独分类,我相信这会更快?
这是我目前使用的代码:
import numpy as np
import pandas as pd
from google.cloud import language
client = language.LanguageServiceClient()
def classify(string):
document = language.types.Document(content=string, type=language.enums.Document.Type.PLAIN_TEXT)
sentiment = client.analyze_sentiment(document=document).document_sentiment
return (sentiment.score, sentiment.magnitude)
def sentiment_analysis_df(df):
df['sentiment_score'] = np.zeros(len(df))
df['sentiment_magnitude'] = np.zeros(len(df))
for i in range(len(df)):
score, magnitude = classify(df['comment'].iloc[i])
df['sentiment_score'].iloc[i] = score
df['sentiment_magnitude'].iloc[i] = magnitude
# Other steps including saving dataframe as CSV are done here
我在这里看到了另外两个提出类似问题的帖子,here 和 here,但第一个假设句号用于字符串分隔(在我的情况下不正确,因为许多字符串由多个句子),第二个只有讨论速率限制和成本的答案。
【问题讨论】:
标签: python pandas google-cloud-platform nlp