python 調用圖靈機器人

import json
import urllib.request
while 1:
    try:
        api_url = "http://openapi.tuling123.com/openapi/api/v2"
        text_input = input('我:')
        if text_input == 'exit':
            break
        req = {
            "reqType": 0,  # 輸入類型 0-文本, 1-圖片, 2-音頻
            "perception":  # 信息參數
            {
                "inputText":  # 文本信息
                {
                    "text": text_input
                },

                "selfInfo":  # 用戶參數
                {
                    "location":
                    {
                        "city": "深圳",  # 所在城市
                        "province": "廣東",  # 省份
                        "street": "紅花嶺路"  # 街道
                    }
                }
            },
            "userInfo":
            {
                "apiKey": "347b39ee228b4b109dae7270cc08d3c8",  # 改爲自己申請的key
                "userId": "0001"  # 用戶唯一標識(隨便填, 非密鑰)
            }
        }
        # print(req)
        # 將字典格式的req編碼爲utf8
        req = json.dumps(req).encode('utf8')
        # print(req)
        http_post = urllib.request.Request(api_url, data=req, headers={'content-type': 'application/json'})
        response = urllib.request.urlopen(http_post)
        response_str = response.read().decode('utf8')
        # print(response_str)
        response_dic = json.loads(response_str)
        # print(response_dic)
        intent_code = response_dic['intent']['code']
        results_text = response_dic['results'][0]['values']['text']
        print('機器人1號:', results_text)
        # print('code:' + str(intent_code))
    except KeyError:
        print('出錯啦~~, 下次別問這樣的問題了')

注意:1,圖靈機器人規定,信息必須是json模式。所以需要data=json.dumps(req).encode('utf8'),並且編碼胃utf8.

2,返回來的信息需要先解碼,然後再從json轉爲python 數據結構。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章