Python调用图灵api进行聊天

 · 2019-2-24 · 次阅读


不说废话,直接放代码:

import json
import urllib.request
def tuling(text_input):
    api_url = "http://openapi.tuling123.com/openapi/api/v2"
    req = {
        "perception":
        {
            "inputText":
            {
                "text": text_input
            },

            "selfInfo":
            {
                "location":
                {
                    "city": "珠海",
                    "province": "广东",
                    "street": "港湾大道"
                }
            }
        },
        "userInfo": 
        {
            "apiKey": "d99fcd9669714dd6aa0ab303cfa4f3ae",
            "userId": "OnlyUseAlphabet"
        }
    }
    req = json.dumps(req).encode('utf8')
    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')
    response_dic = json.loads(response_str)
    results_text = response_dic['results'][0]['values']['text']
    print('图灵:' +results_text )
    return
while True:
    tuling(text_input = input('我:'))