调用图灵机器人接口进行聊天

import urllib,urllib2
import sys
import json
import os

reload(sys)
sys.setdefaultencoding('utf-8')

API_KEY = '8edce3ce905a4c1dbb965e6b35c3834d'
raw_TULINURL = "http://www.tuling123.com/openapi/api?key=%s&info=" % API_KEY
file = 'C:\\Users\\Administrator\\PycharmProjects\\q\\tl.txt'

if os.path.exists(file):
    os.remove(file)
else:
    print('no such file:%s' % file)
fout = open(file, 'a')
fout.write("您已开始进入与图灵机器人的交谈\n"+'\n')
def result(queryStr):


        TULINURL = "%s%s" % (raw_TULINURL,urllib2.quote(queryStr))
        req = urllib2.Request(url=TULINURL)
        result = urllib2.urlopen(req).read()
        hjson=json.loads(result)
        length=len(hjson.keys())
        content=hjson['text']
        #return content
        if length==3:
            return content+hjson['url']
        elif length==2:
            return content

if __name__=='__main__':
    print "你好,请输入内容:".decode('utf-8')
    queryStr = raw_input(":".decode('utf-8'))
    print type(queryStr.decode('gbk'))
    fout.write(queryStr.decode('gbk') + '\n')
    for i in xrange(3):
        contents=result(queryStr)
        print contents
        fout.write(contents + '\n')
    fout.write('\n')

你可能感兴趣的:(python)