用python写的一个可以多轮对话的聊天助手或机器人,也可以用来查询和下载全网音乐,聊天数据存放在Access数据库中

废话不多说。。。开玩笑还是要说点废话的,我的聊天数据存放在access数据库中

如图:

这是里面的内容

可以看到回复数据2这个表里一共有两个字段一个是问题一个是答案

如果没有access数据库的大家可以自行搜索安装

1,安装库

pip install pyodbc
pip install pandas
pip install random
pip install time
pip install requests
pip install jsonpath

如果大家嫌弃官网安装太慢的话我这里有一个阿里官方镜像源https://mirrors.aliyun.com/pypi/simple/

用法如下面这个代码一样,要加上-i 参数

pip install pyodbc -i https://mirrors.aliyun.com/pypi/simple/

2.代码里面的下载音乐部分的代码是基于这位博主的代码上进行的二次修改

原文在这:http://t.csdnimg.cn/2wmLS

废话说完了,上代码复制就能用,前提是你得有数据库,当然你也可以修改代码,代码可能会有一点bug请见谅

import pyodbc
import pandas as pd
import random
import time
import requests
import jsonpath
import os
# 记录开始时间
start_time = time.time()
# 连接Access数据库
conn_str = r'DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=D:\新建文件夹 (2)\OneDrive\文档\回复数据1.accdb;'
cnxn = pyodbc.connect(conn_str)
# 读取Access数据库中的表格数据
sql_query = "SELECT * FROM 回复数据2"
data = pd.read_sql(sql_query, cnxn)
print(data)# 输出表单
# 获取问题和答案列表
questions = data['问题'].tolist()
answers = data['答案'].tolist()
# 定义匹配度通过关键词计数的函数
def get_match_score(user_input, question):
    score = 0
    if question is None:
        return score
    words = question.split()
    for word in user_input.split():
        if word in words:
            score += 1
    return score
def song_download(url, title, author, path):
    os.makedirs(path, exist_ok=True)
    mp3_path = os.path.join(path, f"{title}-{author}.mp3")
    print('歌曲:{0}-{1},正在下载...'.format(title, author))
    content = requests.get(url).content
    with open(file=mp3_path, mode='wb') as f:
        f.write(content)
    print('下载完毕,{0}-{1},请试听'.format(title, author))
# 欢迎信息
print("欢迎使用知识模型!请输入您的问题,或输入'退出'结束对话。")

end_time = time.time()
# 计算运行时间
elapsed_time = end_time - start_time
print("代码运行时间:", elapsed_time, "秒")

# 对话循环
while True:
    # 获取用户输入的问题
    user_input = input("您: ")

    # 判断是否退出对话
    if user_input.lower() == '退出':
        print("再见!")
        time.sleep(1)
        print("---程序结束---")
        break

    # 判断是否下载音乐
    elif user_input.lower()[0:2] == '下载':
         if user_input.lower()[0:2] == '下载':# 如果输入的字符的前两位为下载则进入音乐下载循环
             print("正在加载...")
             time.sleep(0.5)# 延迟0.5秒
             while user_input.lower()[0:2] == '下载':# 如果输入的字符的前两位为下载则进入音乐下载循环
                 name = input("请输入歌曲名称:(输入y退出)")
                 if name == "y":
                     break
                 def get_music_name():
                     #global nama
                     #name = nama
                     print("1.网易云:netease\n2.QQ:qq\n3.酷狗:kugou\n4.酷我:kuwo\n5.百度:baidu\n6.喜马拉雅:ximalaya")
                     xuhao_dict = {}
                     xuhao_dict[1] = "netease"
                     xuhao_dict[2] = "qq"
                     xuhao_dict[3] = "kugou"
                     xuhao_dict[4] = "kuwo"
                     xuhao_dict[5] = "baidu"
                     xuhao_dict[6] = "ximalaya"

                     # 下面这个定义修复了输入不是数字会报错的问题
                     def get_clbc2():
                         while True:

                             num = input("输入音乐平台类型序号:")
                             if num.isnumeric():
                                 return int(num)
                             else:
                                 time.sleep(0.5)
                                 print('人家输入的是歌曲的版本序号,你个傻狗!!!')
                                 print('')
                                 time.sleep(0.5)
                                 print('请重新输入歌曲的版本序号')
                                 print('')

                     num = get_clbc2()

                     print('正在搜索....')
                     platform = xuhao_dict[num]
                     print("-------------------------------------------------------")
                     url = 'https://music.liuzhijin.cn/'
                     headers = {
                         "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",
                         "x-requested-with": "XMLHttpRequest",
                     }
                     param = {
                         "input": name,
                         "filter": "name",
                         "type": platform,
                         "page": 1,
                     }
                     res = requests.post(url=url, data=param, headers=headers)
                     json_text = res.json()

                     titles = jsonpath.jsonpath(json_text, '$..title')
                     authors = jsonpath.jsonpath(json_text, '$..author')
                     urls = jsonpath.jsonpath(json_text, '$..url')

                     if titles:
                         songs = list(zip(titles, authors, urls))
                         for index, song in enumerate(songs):
                             print(f"{index + 1}. {song[0]} - {song[1]}")
                         print("-------------------------------------------------------")
                         # 下面这个定义修复了输入不是数字会报错的问题
                         def get_clbc2():
                             while True:
                                chosen_index = input("请输入您想下载的歌曲版本:")

                                if chosen_index.isnumeric():
                                    return int(chosen_index)
                                else:
                                    print("")
                                    print('请重新输入歌曲序号!!!')
                                    print('')

                         chosen_index = get_clbc2()  # 将函数赋值给chosen_index
                         chosen_index = chosen_index - 1 # 使下载的歌曲版本的索引从1开始
                         if chosen_index >= 0 and chosen_index < len(songs):
                             # download_path = input("请输入下载路径:")
                             download_path = 'E:\视屏剪辑\yinyue'  # 下载路径
                             print('当前下载路径:', download_path)
                             song_download(songs[chosen_index][2], songs[chosen_index][0], songs[chosen_index][1], download_path)
                     else:
                         print("对不起,暂无搜索结果!")
                 get_music_name()
                 pass
         else:
             pass
# 初始化最高匹配度
    max_score = -1
    best_answer = ""

    # 搜索匹配度最高的回答
    for i in range(len(questions)):
        score = get_match_score(user_input, questions[i])
        if score > max_score:
            max_score = score
            best_answer = answers[i]
        elif score == max_score:  # 处理相同匹配度的情况
            if random.randint(0, 1) == 1:  # 随机选择一条回答
                best_answer = answers[i]

    # 输出回答逐个字符的方法
    if max_score == 0:
        bnhd = "陈文茜:我不理解你在说什么。"
        for bnhd1 in bnhd:
            print(bnhd1, end='')  # 每输出一个字符后立即刷新输出缓冲区
            time.sleep(0.1)  # 暂停0.1秒
        #print("")  # 输出完整回答后换行



    else:
        print("陈文茜:", end="")

        if best_answer is not None:# if best_answer is not None:中的is not None用来判断你的表的答案是否为空
            for char in best_answer:# 如果不为空则执行这个
                print(char, end='', flush=True)  # 每输出一个字符后立即刷新输出缓冲区
                time.sleep(0.1)  # 暂停0.1秒
        else:
            bnhd = "陈文茜:我不理解。"# 为空则执行这个
            for bnhd1 in bnhd:
                print(bnhd1, end='')  # 每输出一个字符后立即刷新输出缓冲区
                time.sleep(0.1)# 延迟0.1秒
    print("")  # 输出完整回答后换行
"""    end_time = time.time()
    # 计算运行时间
    elapsed_time = end_time - start_time
    print("运行时间:", elapsed_time, "秒")"""

效果如图:

  • 10
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值