import re,sys#导入模块
from time import strftime,gmtime
f=open('main.txt','r',encoding='utf-8')#以读取的方式打开txt数据库
main=f.read()#读取txt文件到缓存并赋值给main
def welcome():
print('先生,输入$可以关闭我嚛-')
time_return()#时间问候
#while True:
question=input('...')#等待用户输入问题
open_function(question)
find_return(question)
def open_function(function):
if function=='$':
print('后会有期!')
sys.exit()
else:
pass
def time_return():
data=strftime("%Y年%m月%d日 %H:%M")#获取当前时间
print('当前日期为{}'.format(data))#打印当前时间
hour=int(strftime("%H"))#获取当前小时
if 4<hour<12:#不同的时间段不同回答
print('上午好,先生')
elif 11<hour<17:
print('中午好,先生')
elif 16<hour<24:
print('晚上好')
else:
print('这么晚还不睡,和我的粑粑一起变秃头小宝贝叭~~~')
def find_return(question):
#通过正则查找方便快捷
try:#正向查找
answer=re.findall('{}@(.*?)\n'.format(question),main,re.S)[0]#通过问题寻找答案
print(answer)#打印回答
except:#反向查找
answer=re.findall('\n(.*?)@{}\n'.format(question),main)[0]#通过答案寻找问题
print(answer)
welcome()
今天对问答机器人做了如下功能添加:1.增加根据时间在用户打开文件时实现问候2.输入特定字符关闭
明天将会增加模糊搜索功能
附上运行图