使用Python调用IBM Watson NLU遇TypeError错误的排查与解决
错误原因分析及解决方案
这个TypeError: cannot convert dictionary update sequence element #0 to a sequence报错主要有两个核心原因:
传入
text参数的数据类型错误:你把data定义成了包含数字和字符串的列表([1, "your-text-here"]),但Watson NLU的analyze方法要求text参数必须是纯字符串,不能是列表或混合类型的容器。当你把列表传给text时,内部处理逻辑试图把它转换成预期的格式,就触发了这个类型错误。Features参数的调用方式不符合库的要求:你原来用
features=[nluFeatures.Keywords(), ...]这种列表形式传参,但对于Watson Developer Cloud的这个版本,features参数需要传入的是Features对象,而不是多个Feature类实例组成的列表。这种传参方式会导致库内部解析参数时出错,也是触发错误的原因之一。
修正后的代码
import watson_developer_cloud as WDC from watson_developer_cloud.natural_language_understanding_v1 import Features, KeywordsOptions, EntitiesOptions, CategoriesOptions, EmotionOptions, SentimentOptions # 初始化NLU服务实例,替换成你的账号密码 nlu = WDC.NaturalLanguageUnderstandingV1('2017-02-27', username='yourusername', password='yourpassword') # 直接传入纯字符串作为待分析文本 data = ("I've seen things you people wouldn't believe. Attack ships on fire off the shoulder of Orion. I watched C-beams glitter in the dark near the Tannhauser Gate. All those moments will be lost in time, like tears in rain. Time to die.") def nlu_analyze(): # 使用Features类封装各个分析选项,这是库要求的正确传参方式 response = nlu.analyze( text=data, features=Features( keywords=KeywordsOptions(), entities=EntitiesOptions(), categories=CategoriesOptions(), emotion=EmotionOptions(), sentiment=SentimentOptions() ) ) return response response = nlu_analyze() # 打印各分析结果 print(response["keywords"]) print(response["entities"]) print(response["categories"]) print(response["emotion"]) print(response["sentiment"])
内容的提问来源于stack exchange,提问作者blueworld
相关产品推荐
相关产品推荐

