导入***requests***和***json***库
import requests
import json
创建一个***循环***,使其能一直运作下去
用文本***text***来替代聊天框
while True:
text = input("你说的:")
再来看青云客的api接口:
‘http://api.qingyunke.com/api.php?key=free&appid=0&msg=你好’
直接打开这个网页显示出的是:
‘{“result”:0,“content”:“好啊~你更好”}’
所以直接锁定编写流程:
##1.向网站发送请求,替代上文的“你好”
url = 'http://api.qingyunke.com/api.php?key=free&appid=0&msg=%s'%text
header = {
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.141 Safari/537.36'
}
response = requests.get(url,headers=header)
response.encoding = 'utf-8'
## 2.获取响应,将其输出到文本中
text_json = json.loads(response.text)
context = "AI说:%s"%text_json['content']
print(context)
最后可以加一个if的判断,判断是否结束循环
if text == '拜拜':
print()
break
else:
#其余的代码
直至最后看一眼代码
#By NMPE Shader
#2021-1-15
import requests
import json
if __name__ == '__main__':
while True:
text = input("你说的:")
if text == '拜拜':
print()
break
else:
url = 'http://api.qingyunke.com/api.php?key=free&appid=0&msg=%s'%text
header = {
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.141 Safari/537.36'
}
response = requests.get(url,headers=header)
response.encoding = 'utf-8'
text_json = json.loads(response.text)
context = "AI说:%s"%text_json['content']
print(context)