在python中为Watson NLU调用多个API



我正在研究Watson NLU,我需要对问卷数据进行分析。大约300个答案来自不同的人。我可以在"……"上运行它。格式文本,但我想得到一些帮助,我如何运行它所有的300在一次运行。我目前的输入是在excel与ID列。谢谢你调查此事。

nlu_api_key = "MY API KEY"
nlu_url = "https://api.eu-gb.natural-language-understanding.watson.cloud.ibm.com/instances/MY INSTANCE"

import json
from ibm_watson import NaturalLanguageUnderstandingV1
from ibm_cloud_sdk_core.authenticators import IAMAuthenticator
from ibm_watson.natural_language_understanding_v1 import Features, EntitiesOptions, KeywordsOptions, CategoriesOptions,SentimentOptions
import pandas as pd

gtm_Q6 = pd.read_excel(r'C:Users...INPUT FILE.xlsx', sheet_name='OUPUT1')
print(gtm_Q6)

authenticator = IAMAuthenticator(nlu_api_key)
natural_language_understanding = NaturalLanguageUnderstandingV1(
version='2020-08-01',
authenticator=authenticator)
natural_language_understanding.set_service_url(nlu_url)
response = natural_language_understanding.analyze(
text='Where is the firetruck with the flaming paint the tigers on top?',
features=Features(
entities=EntitiesOptions(emotion=True, sentiment=True, limit=5),
keywords=KeywordsOptions(emotion=True, sentiment=True,limit=5),
categories=CategoriesOptions(limit=3),
sentiment=SentimentOptions(targets=['investments']) #sentiment=SentimentOptions(targets=['stocks'])
)).get_result()
print(json.dumps(response, indent=2))
<表类>RESP_ID回答tbody><<tr>Q6_109.000000团队建设Q6_110.000000技术和服务之间的启用和协调Q6_111.000000技能构建Q6_113.000000速度到正确的资源Q6_114.000000当前变更的实用性信息

所以解决方案是py T.J. Crowder在Python中提供的:这是他最初回答的链接:如何摆脱"n"one_answers";& # 39;& # 39;";在json文件

json_arr = []
for text in gtm_Q6_df['ANSWER']:
response = natural_language_understanding.analyze(
text=text,language = 'en',
features=Features(
entities=EntitiesOptions(sentiment=True,emotion=False,limit=3),
categories=CategoriesOptions(limit=3),
#sentiment=SentimentOptions(EntitiesOptions)
)).get_result()

#text = ("{ Answer: " + text + "}")
json_arr.append(text)
json_arr.append (response) # <==== change is here
with open(r'C:Users...DocumentsPython NLPWATSON NLUOUTPUT JSONdata.json','w') as outline: #with open('data.json','w') as outline: ## data.json is the output file created ## the file can be renamed
json.dump(json_arr,outline, indent = 2) # indent = 2 creates the pretty json!!

print("break")
print(json_arr)

最新更新