图灵聊天机器人API1.0与API2.0的使用方法



API1.0使用方法:

# file TurlingApi1.py
import requests
import json
import yuyinhecheng as hc

def Tuling(words):
    Tuling_API_KEY = "你的AK"

    body = {"key":Tuling_API_KEY,"info":words.encode("utf-8")}

    url = "http://www.tuling123.com/openapi/api"
    r = requests.post(url,data=body)
    if r:
        date = json.loads(r.text)
        print (list(date))
        print(date['text'])
        hc.speak(date['text'])
        try:
            for mylist in date['list']:
                str2=mylist[list(mylist)[0]]
                print(str2)
                hc.speak(str2)
                print(mylist)
        except:
            pass
        return date["text"]
    else:
        return None


if __name__=='__main__':
    Tuling('红烧肉菜谱')


API2.0使用方法:

# file TurlingApi2.py
import json
import urllib.request
import yuyinhecheng as hc

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": "你的AK",
        "userId": "demo"
    }
    }
    # 将字典格式的req编码为utf8
    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')
    print(response_str)
    response_dic = json.loads(response_str)
    print(response_dic)

    intent_code = response_dic['intent']['code']
    if (int(str(intent_code)[0])<4):
        print (str(intent_code))
        listp=list(response_dic['intent']['parameters'])
        print (response_dic['intent']['parameters'][listp[0]])
        str2=response_dic['results'][0]['values']['text']
        print(str2)
        hc.speak(str2)
        if ((intent_code==10003)or (intent_code==10015)) :
            for myresults in response_dic['results'][1]['values']['news']:
                print (myresults)
                print(myresults['name'])
                hc.speak(myresults['name'])
    else:
        print('错误。错误代码:' + str(intent_code))

if __name__=='__main__':
    Tuling('水煮鱼菜谱')


语言合成:

#file yuyinhecheng.py

import win32com
import pyttsx3
def speak(str):
    engine = pyttsx3.init()
    voices = engine.getProperty('voices')
    engine.setProperty('voice',voices[3].id)
    engine.say(str)
    engine.runAndWait()

猜你喜欢

转载自blog.csdn.net/www_rsqdz_net/article/details/79680461