基于python的对话机器人bot项目开发(二)

基于python的对话机器人bot项目开发(二)

熟练使用库

把程序按功能划分成文件

pybot.txt:
你好,我很好
谢谢,不客气
再见,拜拜
pybot_eto.py

def eto_command(command):
    eto, year_str = command.split()
    year = int(year_str)
    number_of_eto = (year + 8) % 12
    eto_tuple = ("子", "丑", "寅", "卯", "辰", "巳", "午", "未", "申", "酉", "戌", "亥")
    eto_name = eto_tuple[number_of_eto]
    response = f'{year}年对应的干支为「{eto_name}」。'
    return response

pybot.py

from pybot_eto import eto_command

def len_command(command):
    cmd, text = command.split()
    length = len(text)
    response = f'字符串的长度为{length}'
    return response

def wareki_command(command):
    wareki, year_str = command.split()
    year = int(year_str)
    if year >= 2019:
        reiwa = year - 2018
        response = f'和历{year}年、令和{reiwa}年'
    elif year >= 1989:
        heisei = year - 1988
        response = f'和历{year}年、平成{heisei}年'
    else:
        response = f'和历{year}年、平成前的时代'
    return response

command_file = open('pybot.txt', encoding='utf-8')
raw_data = command_file.read()
command_file.close()
lines = raw_data.splitlines()

bot_dict = {}
for line in lines:
    word_list = line.split(',')
    key = word_list[0]
    response = word_list[1]
    bot_dict[key] = response

while True:
    command = input('pybot> ')
    response = ''
    for message in bot_dict:
        if message in command:
            response = bot_dict[message]
            break

    if '和历' in command:
        response = wareki_command(command)
    if '长度' in command:
        response = len_command(command)
    if '干支' in command:
        response = eto_command(command)

    if not response:
        response = '我不知道你在说什么'
    print(response)

    if '再见' in command:
        break

运行:

pybot> 干支 2020
2020年对应的干支为「子」。
pybot> 干支 1976
1976年对应的干支为「辰」。
pybot> 牛排
我不知道你在说什么
pybot> 长度 规范沟沟壑壑v和
字符串的长度为8
pybot> 再见
拜拜

使用标准库

其他同上,加入标准库
pybot_random.py

import random

def choice_command(command):
    data = command.split()
    choiced = random.choice(data)
    response = f'选择结果为"{choiced}"'
    return response

def dice_command():
    num = random.randrange(1, 7)
    response = f'投掷数字为 {num}'
    return response

pybot.py

from pybot_eto import eto_command
from pybot_random import choice_command, dice_command

def len_command(command):
    cmd, text = command.split()
    length = len(text)
    response = f'字符串的长度为{length} '
    return response

def wareki_command(command):
    wareki, year_str = command.split()
    year = int(year_str)
    if year >= 2019:
        reiwa = year - 2018
        response = f'和历{year}年、令和{reiwa}年'
    elif year >= 1989:
        heisei = year - 1988
        response = f'和历{year}年、平成{heisei}年'
    else:
        response = f'和历{year}年、平成前的时代'
    return response
command_file = open('pybot.txt', encoding='utf-8')
raw_data = command_file.read()
command_file.close()
lines = raw_data.splitlines()

bot_dict = {}
for line in lines:
    word_list = line.split(',')
    key = word_list[0]
    response = word_list[1]
    bot_dict[key] = response

while True:
    command = input('pybot> ')
    response = ''
    for message in bot_dict:
        if message in command:
            response = bot_dict[message]
            break

    if '和历' in command:
        response = wareki_command(command)
    if '长度' in command:
        response = len_command(command)
    if '干支' in command:
        response = eto_command(command)
    if '选择' in command:
        response = choice_command(command)
    if '骰子' in command:
        response = dice_command()

    if not response:
        response = '我不知道你在说什么'
    print(response)

    if '再见' in command:
        break

运行:

pybot> 选择 拉面 咖喱 乌冬面
选择结果为"拉面"
pybot> 骰子
投掷数字为 2
pybot> 骰子
投掷数字为 3

创建datetime模块,处理日期时间

使用datetime模块创建命令
pybot_datetime.py

from datetime import date, datetime

def today_command():
    today = date.today()
    response = f'今天的日期是 {today}'
    return response

def now_command():
    now = datetime.now()
    response = f'当前的时间是 {now}'
    return response

def weekday_command(command):
    data = command.split()
    year = int(data[1])
    month = int(data[2])
    day = int(data[3])
    one_day = date(year, month, day)

    weekday_str = '一二三四五六日'
    weekday = weekday_str[one_day.weekday()]

    response = f'{one_day} 是 星期 {weekday}'
    return response

pybot.py

from pybot_eto import eto_command
from pybot_random import choice_command, dice_command
from pybot_datetime import today_command, now_command, weekday_command

def len_command(command):
    cmd, text = command.split()
    length = len(text)
    response = f'字符串的长度为{length} '
    return response

def wareki_command(command):
    wareki, year_str = command.split()
    year = int(year_str)
    if year >= 2019:
        reiwa = year - 2018
        response = f'和历{year}年、令和{reiwa}年'
    elif year >= 1989:
        heisei = year - 1988
        response = f'和历{year}年、平成{heisei}年'
    else:
        response = f'和历{year}年、平成前的时代'
    return response
command_file = open('pybot.txt', encoding='utf-8')
raw_data = command_file.read()
command_file.close()
lines = raw_data.splitlines()

bot_dict = {}
for line in lines:
    word_list = line.split(',')
    key = word_list[0]
    response = word_list[1]
    bot_dict[key] = response

while True:
    command = input('pybot> ')
    response = ''
    for message in bot_dict:
        if message in command:
            response = bot_dict[message]
            break

    if '和历' in command:
        response = wareki_command(command)
    if '长度' in command:
        response = len_command(command)
    if '干支' in command:
        response = eto_command(command)
    if '选择' in command:
        response = choice_command(command)
    if '骰子' in command:
        response = dice_command()
    if '今天' in command:
        response = today_command()
    if '当前' in command:
        response = now_command()
    if '星期' in command:
        response = weekday_command(command)

    if not response:
        response = '我不知道你在说什么'
    print(response)

    if '再见' in command:
        break

运行:

pybot> 今天
今天的日期是 2024-07-22
pybot> 当前
当前的时间是 2024-07-22 04:53:18.820514
pybot> 星期 1976 11 06
1976-11-06 是 星期 六
pybot> 星期 1988 07 31
1988-07-31 是 星期 日
pybot> 

从列表、元组和字符串中提取数据

修改pybot_random.py

import random

def choice_command(command):
    data = command.split()
    choiced = random.choice(data[1:]) #修改部分
    response = f'选择结果为"{choiced}"'
    return response

def dice_command():
    num = random.randrange(1, 7)
    response = f'投掷数字为 {num}'
    return response

运行pybot.py:

pybot> 选择 拉面 咖喱 乌冬面
选择结果为"乌冬面"
pybot> 选择 拉面 咖喱 乌冬面
选择结果为"乌冬面"
pybot> 选择 拉面 咖喱 乌冬面
选择结果为"拉面"
pybot> 选择 面窝 热干面 京果条
选择结果为"热干面"
pybot> 

使用数学函数进行计算

平方根命令pybot_math.py

import math

def sqrt_command(command):
    sqrt, number_str = command.split()
    x = int(number_str)
    sqrt_x = math.sqrt(x)
    response = f'{x} 的平方根是 {sqrt_x} '
    return response

创建一个防止异常发生的程序

pybot.py

from pybot_eto import eto_command
from pybot_random import choice_command, dice_command
from pybot_datetime import today_command, now_command, weekday_command

def len_command(command):
    cmd, text = command.split()
    length = len(text)
    response = f'字符串的长度为{length} '
    return response

def wareki_command(command):
    wareki, year_str = command.split()
    try:    # 添加try关键字
        year = int(year_str)
        if year >= 2019:
            reiwa = year - 2018
            response = f'和历{year}年、令和{reiwa}年'
        elif year >= 1989:
            heisei = year - 1988
            response = f'和历{year}年、平成{heisei}年'
        else:
            response = f'和历{year}年、平成前的时代'
    except ValueError:    # 添加except关键字
        response = '请指定数值'
    return response
command_file = open('pybot.txt', encoding='utf-8')
raw_data = command_file.read()
command_file.close()
lines = raw_data.splitlines()

bot_dict = {}
for line in lines:
    word_list = line.split(',')
    key = word_list[0]
    response = word_list[1]
    bot_dict[key] = response

while True:
    command = input('pybot> ')
    response = ''
    for message in bot_dict:
        if message in command:
            response = bot_dict[message]
            break

    if '和历' in command:
        response = wareki_command(command)
    if '长度' in command:
        response = len_command(command)
    if '干支' in command:
        response = eto_command(command)
    if '选择' in command:
        response = choice_command(command)
    if '骰子' in command:
        response = dice_command()
    if '今天' in command:
        response = today_command()
    if '当前' in command:
        response = now_command()
    if '星期' in command:
        response = weekday_command(command)

    if not response:
        response = '我不知道你在说什么'
    print(response)

    if '再见' in command:
        break

运行:

pybot> 和历 元年
请指定数值
pybot> 和历 1988
和历1988年、平成前的时代
pybot> 和历 2014
和历2014年、平成26年
pybot>

熟练使用异常处理

pybot.py

from pybot_eto import eto_command
from pybot_random import choice_command, dice_command
from pybot_datetime import today_command, now_command, weekday_command

def len_command(command):
    cmd, text = command.split()
    length = len(text)
    response = f'字符串的长度为{length} '
    return response

def wareki_command(command):
    wareki, year_str = command.split()
    if year_str.isdigit():   # 确定是否能转换成数值
        year = int(year_str)
        if year >= 2019:
            reiwa = year - 2018
            response = f'和历{year}年、令和{reiwa}年'
        elif year >= 1989:
            heisei = year - 1988
            response = f'和历{year}年、平成{heisei}年'
        else:
            response = f'和历{year}年、平成前的时代'
    else:    # except关键字改写成else语句
        response = '请指定数值'
    return response

command_file = open('pybot.txt', encoding='utf-8')
raw_data = command_file.read()
command_file.close()
lines = raw_data.splitlines()

bot_dict = {}
for line in lines:
    word_list = line.split(',')
    key = word_list[0]
    response = word_list[1]
    bot_dict[key] = response

while True:
    command = input('pybot> ')
    response = ''
    for message in bot_dict:
        if message in command:
            response = bot_dict[message]
            break

    if '和历' in command:
        response = wareki_command(command)
    if '长度' in command:
        response = len_command(command)
    if '干支' in command:
        response = eto_command(command)
    if '选择' in command:
        response = choice_command(command)
    if '骰子' in command:
        response = dice_command()
    if '今天' in command:
        response = today_command()
    if '当前' in command:
        response = now_command()
    if '星期' in command:
        response = weekday_command(command)

    if not response:
        response = '我不知道你在说什么'
    print(response)

    if '再见' in command:
        break

pybot_datetime.py

from datetime import date, datetime

def today_command():
    today = date.today()
    response = f'今天的日期是 {today}'
    return response

def now_command():
    now = datetime.now()
    response = f'当前的时间是 {now}'
    return response

def weekday_command(command):
    try:    # 添加try关键字
        data = command.split()
        year = int(data[1])
        month = int(data[2])
        day = int(data[3])
        one_day = date(year, month, day)

        weekday_str = '一二三四五六日'
        weekday = weekday_str[one_day.weekday()]

        response = f'{one_day} 是 星期 {weekday}'
    except IndexError:    # 对应IndexError
        response = '指定3个值(年月日)'
    except ValueError:   # 对应ValueError
        response = '指定正确的日期'
    return response

运行:

pybot> 和历 元年
请指定数值
pybot> 星期 2020 5
指定3个值(年月日)
pybot> 星期 2020 2 30
指定正确的日期
pybot> 星期 1988 07 31
1988-07-31 是 星期 日
pybot> 

输出异常的内容

pybot.py

from pybot_eto import eto_command
from pybot_random import choice_command, dice_command
from pybot_datetime import today_command, now_command, weekday_command

def len_command(command):
    cmd, text = command.split()
    length = len(text)
    response = f'字符串的长度为{length} '
    return response

def wareki_command(command):
    wareki, year_str = command.split()
    if year_str.isdigit():
        year = int(year_str)
        if year >= 2019:
            reiwa = year - 2018
            response = f'和历{year}年、令和{reiwa}年'
        elif year >= 1989:
            heisei = year - 1988
            response = f'和历{year}年、平成{heisei}年'
        else:
            response = f'和历{year}年、平成前的时代'
    else:
        response = '请指定数值'
    return response

command_file = open('pybot.txt', encoding='utf-8')
raw_data = command_file.read()
command_file.close()
lines = raw_data.splitlines()

bot_dict = {}
for line in lines:
    word_list = line.split(',')
    key = word_list[0]
    response = word_list[1]
    bot_dict[key] = response

while True:
    command = input('pybot> ')
    response = ''
    try:    # 添加try关键字
        for message in bot_dict:
            if message in command:
                response = bot_dict[message]
                break

        if '和历' in command:
            response = wareki_command(command)
        if '长度' in command:
            response = len_command(command)
        if '干支' in command:
            response = eto_command(command)
        if '选择' in command:
            response = choice_command(command)
        if '骰子' in command:
            response = dice_command()
        if '今天' in command:
            response = today_command()
        if '当前' in command:
            response = now_command()
        if '星期' in command:
            response = weekday_command(command)

        if not response:
            response = '我不知道你在说什么'
        print(response)

        if '再见' in command:
            break

    except Exception as e:    # 添加except 关键字
        print('发生了意想不到的错误')
        print(f'* 种类: {type(e)}')
        print(f'* 内容: {e}')

运行:

pybot> 选择
发生了意想不到的错误
* 种类: <class 'IndexError'>
* 内容: Cannot choose from an empty sequence
pybot> 干支 丸子
发生了意想不到的错误
* 种类: <class 'ValueError'>
* 内容: invalid literal for int() with base 10: '丸子'
pybot> 选择 热干面 猪脚饭 面窝
选择结果为"热干面"
pybot> 

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值