如何为API响应中的单词分配数字

时间:2018-09-09 17:49:32

标签: python nltk ibm-watson

我已经使用Watson Knowledge Studio创建了一个自定义的机器学习模型,并部署到了NLU服务。我也设法用python访问我的模型。我的自定义模型旨在识别特定的实体类型,例如(建议,取消,意识等)。我想做的是从API JSON响应中提取这些实体类型,并为它们分配一个数字(例如,建议= 1,取消= 2,意识= 3,等等),然后将它们与示例文本(例如, “我想取消对Gameloft的订阅。”)到具有列标题(ID,句子,实体类型)的CSV文件。我已经设法提取实体类型和示例文本并将它们写入.txt文件,但是我需要将它们写入CSV文件。

import json
from watson_developer_cloud import NaturalLanguageUnderstandingV1
from watson_developer_cloud.natural_language_understanding_v1 \
  import Features, EntitiesOptions, KeywordsOptions

natural_language_understanding = NaturalLanguageUnderstandingV1(
  username='**************',
  password='*********',
  version='2018-03-16')

text="I want to cancel my subscription with Gameloft."
response = natural_language_understanding.analyze(
text =text,  
  features=Features(
    entities=EntitiesOptions(
      emotion=True,
      sentiment=True,
      limit=2,
      model="**************"),
    keywords=KeywordsOptions(
      emotion=True,
      sentiment=True,
      limit=2)))



print(json.dumps(response, indent=2)) 

response['keywords'][0]['text']
response ['entities'][0]['type']

if response['entities'][0]['type'] == "Cancellation":
    print ('1')
with open('C:\\Users\\Results.txt', "w") as f:
    for x in response['entities']:
        f.write(x['type'] + ' ')

请帮助我进行以下操作:

如何为实体类型分配数字?

是否有一种方法可以创建一个循环,以加载要由NLU API分析的多个句子/文本?

如何将所有内容(实体类型,文本和分配给实体类型的数字)写入CSV文件?

1 个答案:

答案 0 :(得分:0)

您可以使用字典来映射带有数字的实体类型。 例如

entity_number_dict = {
'Advice': 1,
'Cancellation': 2,
'Awareness': 3
}
print(entity_number_dict[response['entities'][0]['type']])