ValueError: If the `request` argument is set, then none of the individual field arguments should be set

ValueError: If the `request` argument is set, then none of the individual field arguments should be set

我正在使用 Google NLP API 进行情感分析,以提取数据框的情感分数,其中 review 作为我的文本列。我的代码看起来像,

def getSentiments(df):
inserts = 0
df1 = pd.DataFrame(columns = ['Content', 'Sentiment', 'Magnitude', 'ReviewId'])
for index, row in df.iterrows():
    time.sleep(0.5)
    print(index)
    text1 = row['review']
    reviewid = row['review_id']
    texts = []
    sentiments = []    
    magnitudes = []
    salience = []
    try:
        document = analyze_sentiment(text1)
        result = client.analyze_sentiment(document, encoding_type = "UTF8")
        # Get overall sentiment of the input document
        print(u"Document sentiment score: {}".format(result.document_sentiment.score))
       
        sentiments.append(result.document_sentiment.score)
        magnitudes.append(result.document_sentiment.magnitude)
        dfEntitySentiment = pd.DataFrame(columns=['Content','Sentiment','Magnitude', 'ReviewId'])
        dfEntitySentiment['Content'] = text1
        dfEntitySentiment['Sentiment'] = sentiments
        dfEntitySentiment['Magnitude'] = magnitudes
        dfEntitySentiment['ReviewId'] = reviewid
        df1 = df1.append(dfEntitySentiment, ignore_index = True)
        
    except:
        traceback.print_exc()
        continue
return df1

我的 analyze_sentiment 函数看起来像,

def analyze_sentiment(text_content):
client = language_v1.LanguageServiceClient.from_service_account_json(Alteryx.read("#2").iloc[0]['FullPath'])
type_ = language_v1.types.Document.Type.PLAIN_TEXT
language = "en"
document = {"content": text_content, "type": type_, "language": language}
encoding_type = "UTF8"

return document

我收到上述错误,但不确定如何解决。

from google.cloud.language_v1 import enums
from google.cloud.language_v1 import types

我以前使用过的这两个库,但我不得不更新它们。更新库后出现错误。

我已成功复制您的用例,但出现相同的错误消息。

错误来自代码行:

result = client.analyze_sentiment(document, encoding_type = "UTF8")

要解决此问题,您必须明确地将 document 分配给 情感分析请求 的各个字段参数 document,如下所示:

result = client.analyze_sentiment(document = document, encoding_type = "UTF8")

下面是我的样本情感分析请求结果使用更正代码行的结果。

您可以参考此 AnalyzeSentimentRequest 参考文档,了解有关 Google Cloud Natural Language API 的各个字段参数的更多信息。 =17=]

有库更新,根据 Migration Guide,子模块 enumstypes 已被删除。

requestclient.analyze_sentiment 的参数需要遵循以下格式,

result = client.analyze_sentiment(request = {'document': document, 'encoding_type': encoding_type})

这帮助我解决了我的错误。