主要学习内容:
- 使用replace替换字符串内容,实现智能聊天功能
- 对代码进行解耦,使得代码逻辑更加清晰
- 寻找免费的天气api进行实战,实时展示天气
- pip 命令的复习
上代码:
robot.py:
import functions as fun
import time
fun.sayHello()
fun.question()
print('小安:输入time播放当前时间,输入talk我就会和你聊天哦,,其他的功能我还在学习中,扣help寻求帮助,扣88退出\n\n主人现在有什么吩咐吗?\n我:',end='')
while(1):
cmd=input('')
if(cmd=='time'):
fun.sayTime()
elif(cmd=='help'):
fun.helpList()
elif(cmd=='talk'):
print('小安:现在一起聊天吧\n')
elif(cmd=='天气'):
city=input("你想看哪里的天气呢?")
fun.sayWeather(city)
elif(cmd=='88' or cmd=='拜拜' or cmd=='再见'):
print('你可以随时唤醒我哦')
break
else:
print(fun.talk(cmd))
function.py
import time
from datetime import datetime
import requests
import json
def sayHello():
print('''-------------------------------------------''')
print('小安:很高兴为您服务,我是机器人小安,我会聊天还会播报时间哦')
def isage(age):
flag=False
if(age.isdigit()):
age=int(age)
if(age<0):
print('小安:年龄不可能小于0的啦,我虽然年纪小,但是这可骗不到我')
flag=False
elif(age>150):
print('小安:怎么滴,你干脆想长命百岁得了')
flag=False
elif(age<18):
flag=True
# if(sex=='no'):
print('小安:哈哈,主人是个未成年啊')
# else:
# print('从小就和我这样的高科技相处,长大以后肯定是个美女')
elif(age<30):
flag=True
print('小安:正是人生该拼搏的时候,努力努力再努力')
elif(age<45):
flag=True
print('小安:闲下来的日子记得想我喔,还有记得自己也要好好享受生活')
elif(age<60):
flag=True
print('小安:以后无聊找我哦,我有大把的时间')
elif(age<150):
flag=True
print('小安:开心最重要')
# if(sex=='no'):
# print('爷爷,有我的陪伴,相信你以后每天都是开开心心的付过哒')
# else:
# print('奶奶,相信接下来的日子你会喜欢上我')
else:
flag=False
print('小安:抱歉最近有点迷糊,输入数字我才能看懂哦')
return flag
def question():
host_name=input('小安:告诉我你的名字吧,让我更好的了解你\n我:')
flag=False
age=input('小安:我今年一岁了,你呢?\n我:')
# isage(age)
while (isage(age)==False):
age=input("小安:告诉我年龄啦\n我:")
while(1):
sex=input('小安:你是女孩子吗?回答yes或者no哦,我还是个宝宝,理解能力有点差,0.0\n我:')
if (sex=='no' or sex=='yes'):
if (sex=='no'):
sex='男'
print('小安:好的,我知道了啦')
break
elif(sex=='yes'):
sex='女'
print('小安:好的,我知道了啦')
break
else:
print('小安:不要闹啦,快告诉我\n我:')
print(f'小安:主人您叫{host_name},性别是{sex},今年{age}岁啦,是不是很棒')
def sayTime():
day=time.localtime()
print('小安:现在是:',day.tm_year,'年',day.tm_mon,'月',day.tm_mday,'日',day.tm_hour,':',day.tm_min,':',day.tm_sec)
def sayTime2():
dt=datetime.now()
print(dt.strftime('小安:现在是:%Y年%m月%d日 %H:%M:%S'))
def talk(cmd):
answer=cmd.replace("我喜欢你","我也喜欢你").replace("不客气","哈哈,说点别的吧")
answer = answer.replace('你','我').replace('不','').replace('吗','的').replace('?','!').replace('?','!').replace('要','会')
answer=answer.replace("没有","好的撒,有需要随时叫我")
answer=answer.replace("好的","嗯嗯").replace("真棒","谢谢夸奖")
return answer
def helpList():
print(''' -------------------------小安简介---------------------------------
我的名字叫小安,我会聊天会播放时间和天气,还会陪你聊天
1.聊天请扣talk
2.了解当前时间请扣time
3.查询当前天气晴就对我说天气
4.退出程序请扣88或者拜拜或者再见!
5.寻求帮助再次扣help哦,记住啦!
6.小安正在学习中.......
---------------------------------------------------------------''')
def sayWeather(city):
print("小安:好的,收到,查询中.......")
url="https://geoapi.qweather.com/v2/city/lookup?location="+city+"&key=你的KEY"
res = requests.get(url)
location_json=json.loads(res.text)
location_id=location_json["location"][0]["id"]
location_name=location_json["location"][0]["name"]
weather_url="https://devapi.qweather.com/v7/weather/now?location="+location_id+"&key=你的KEY"
res = requests.get(weather_url)
weather_json=json.loads(res.text)
weather=weather_json["now"]["text"]
temp=weather_json["now"]["temp"]
time.sleep(2)
print(f'小安:{location_name}当前天气为:{weather},{temp}摄氏度')
测试界面:
-
对于上面的talk()方法的实现,其实完全就是用的replace去替换字符的,因为本身返回的就是一个对象,这里可以直接用点再次replace就好了
-
把方法和主流程分开,需要了再直接进行调用,整体上会看着舒服很多,把不同功能分开进行解耦是个很棒的体验,这里用as给这个模块取了个别名,用其他就方便些
-
这个就是找的和风天气的免费api啦,自行百度和风天气官网,注册,进入控制台如下界面
然后获取key拼接在url后面,例如:访问下面这个地址:https://devapi.qweather.com/v7/weather/now?location=101010100&key=你的KEY
就是查看北京的天气,自行切换location的值就可以查询不同城市的天气啦。
在这里还有一个就是如何取json中所需要的值,点击此:https://blog.csdn.net/weixin_43631631/article/details/112176637学习一下吧 -
pip 命令的复习
- 使用python -m pip list 命令查看当前pip了多少个模块
- python -m pip install requests 安装requests模块
- python -m pip uninstall requests 卸载requests模块