当前位置: 首页 > news >正文

用Python做有趣的AI项目 2【进阶版】:智能聊天机器人 v2(NLTK + 规则引擎)

🧰 技术栈与工具

Python 3

NLTK(自然语言处理)

datetime(时间处理)

正则表达式 re

规则引擎(我们手动构造)

可选扩展:天气API、情感分析、数据库

📦 第一步:安装依赖

bash
pip install nltk

首次运行需要下载资源:

pythonimport nltk
nltk.download('punkt')
nltk.download('wordnet')
nltk.download('omw-1.4')

📚 第二步:构建核心代码框架

我们先建立一个模块化结构,便于扩展:

python
# chatbot.py
import nltk
import random
import re
import datetime
from nltk.stem import WordNetLemmatizer# 初始化
lemmer = WordNetLemmatizer()
user_name = None  # 简单的上下文记忆# NLP预处理
def normalize(text):text = text.lower()text = re.sub(r'[^\w\s]', '', text)tokens = nltk.word_tokenize(text)return [lemmer.lemmatize(token) for token in tokens]

🧠 第三步:定义“意图”和“规则库”

我们用关键词和模板构建规则库:

python
# 主题关键词与应答模板
intents = {"greeting": {"keywords": ["hello", "hi", "你好", "嗨", "早上好"],"responses": ["你好呀!", "嗨~ 你来了!", "很高兴见到你!"]},"farewell": {"keywords": ["bye", "goodbye", "退出", "再见", "拜拜"],"responses": ["再见,期待下次聊天!", "拜拜啦~", "走好鸭!"]},"name_query": {"keywords": ["你叫什么", "你是谁", "你的名字"],"responses": ["我是一个智能聊天机器人~ 你可以叫我小智。"]},"weather": {"keywords": ["天气", "下雨", "晴天"],"responses": ["今天天气挺不错的(其实我也不知道)😂", "我还不会看天气呢~ 但希望是阳光明媚的!"]},"time": {"keywords": ["几点", "时间", "现在是什么时候"],"responses": ["现在是 " + datetime.datetime.now().strftime("%H:%M")]},"default": {"responses": ["这个我还不太懂呢~", "你可以问我时间、天气、打招呼哦~"]}
}

🎯 第四步:意图识别函数

这个函数识别用户输入属于哪个意图:

pythondef match_intent(user_input):tokens = normalize(user_input)for intent, data in intents.items():for keyword in data.get("keywords", []):if any(keyword in user_input for keyword in data["keywords"]):return intentreturn "default"

🧑‍🏫 第五步:对话生成器(根据意图生成回答)

pythondef generate_response(user_input):global user_nameif "我叫" in user_input:name_match = re.search(r"我叫(\w+)", user_input)if name_match:user_name = name_match.group(1)return f"好的,{user_name},我记住你啦~ 😊"intent = match_intent(user_input)responses = intents[intent]["responses"]if intent == "time":  # 时间动态更新return "现在是 " + datetime.datetime.now().strftime("%H:%M:%S")return random.choice(responses)

🖥️ 第六步:主程序循环

pythondef chat():print("小智:你好呀!我是小智,智能聊天机器人。输入 '退出' 结束聊天~")while True:user_input = input("你:")if user_input.lower() in ['退出', '拜拜', '再见']:print("小智:再见,期待下次聊天!")breakelse:response = generate_response(user_input)print("小智:" + response)if __name__ == "__main__":chat()

✅ 运行效果示例

你:你好
小智:你好呀!你:现在几点了
小智:现在是 14:35:22你:我叫小明
小智:好的,小明,我记住你啦~你:天气怎么样?
小智:我还不会看天气呢~ 但希望是阳光明媚的!你:再见
小智:拜拜啦~

🧩 进阶方向

接入真实天气 API(如 OpenWeather)

接入语音识别 + TTS(如 speech_recognition + pyttsx3)

引入情感分析(如 TextBlob)判断用户心情

多轮对话(Rasa、transformers 或记忆机制)

加入更多主题模块(如笑话、星座、翻译)

接下来我们将继续升级这个聊天机器人,加入以下功能,使其更智能、更实用:

天气查询:接入天气 API,提供实时天气信息。

语音识别与合成:实现语音输入和语音输出,提升交互体验。

情感分析:分析用户情绪,提供更贴心的回应。

多轮对话:支持上下文记忆,实现更自然的对话。

🧰 第一步:安装必要的库

bashpip install nltk pyttsx3 SpeechRecognition requests textblob

🌤️ 第二步:接入天气 API

我们将使用免费的天气 API,如 OpenWeatherMap,获取实时天气信息。

获取 API 密钥
访问 OpenWeatherMap 官网。

注册并登录账户。

在用户中心获取 API 密钥(API Key)。

获取天气信息

pythonimport requestsdef get_weather(city):api_key = '你的API密钥'url = f'http://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}&lang=zh_tw&units=metric'response = requests.get(url)data = response.json()if data['cod'] == 200:main = data['main']weather = data['weather'][0]temperature = main['temp']description = weather['description']return f"{city} 的当前天气是:{description},气温 {temperature}°C。"else:return "抱歉,我无法获取该城市的天气信息。"

#🗣️ 第三步:实现语音识别与合成
语音识别(Speech-to-Text)

pythonimport speech_recognition as srdef listen():recognizer = sr.Recognizer()with sr.Microphone() as source:print("请说话...")audio = recognizer.listen(source)try:text = recognizer.recognize_google(audio, language='zh-TW')print(f"你说:{text}")return textexcept sr.UnknownValueError:print("抱歉,我没听清楚。")return ""except sr.RequestError:print("抱歉,语音服务不可用。")return ""

语音合成(Text-to-Speech)

pythonimport pyttsx3def speak(text):engine = pyttsx3.init()engine.setProperty('rate', 150)  # 语速engine.setProperty('volume', 1)  # 音量engine.setProperty('voice', 'zh')  # 语音engine.say(text)engine.runAndWait()

😊 第四步:实现情感分析

我们将使用 TextBlob 库进行情感分析。

pythonfrom textblob import TextBlobdef analyze_sentiment(text):blob = TextBlob(text)sentiment = blob.sentiment.polarityif sentiment > 0:return "你听起来心情不错!😊"elif sentiment < 0:return "你似乎有些不开心,我能帮忙吗?😟"else:return "你的心情很中立,有什么我可以帮你的吗?🙂"

#🧠 第五步:实现多轮对话
我们将使用一个简单的上下文管理器来记住用户的名字。

pythonuser_name = ""def set_user_name(name):global user_nameuser_name = namereturn f"好的,我记住你叫 {user_name} 了!"def get_user_name():if user_name:return f"你叫 {user_name},对吧?"else:return "你叫什么名字呢?"

🧩 第六步:整合所有功能

pythondef chatbot():print("你好!我是你的智能聊天助手。")while True:print("\n你可以说:'天气' + 城市名,'语音','退出' 等。")text = listen()if '退出' in text:speak("再见!期待下次与您聊天。")breakelif '天气' in text:city = text.split('天气')[-1].strip()if city:weather_info = get_weather(city)speak(weather_info)else:speak("请告诉我你想查询天气的城市。")elif '语音' in text:speak("你好!我可以听你说话并回应你。")elif '我叫' in text:name = text.split('我叫')[-1].strip()if name:response = set_user_name(name)speak(response)else:speak("你叫什么名字呢?")elif '你叫什么' in text:response = get_user_name()speak(response)else:sentiment_response = analyze_sentiment(text)speak(sentiment_response)print(sentiment_response)

🚀 第七步:运行聊天机器人

pythonif __name__ == "__main__":chatbot()

📌 注意事项

天气查询:确保你已经获取并替换了有效的 OpenWeatherMap API 密钥。

语音识别:需要安装麦克风驱动,并确保环境安静以提高识别准确率。

情感分析:TextBlob 的情感分析是基于英文语料库,可能对中文的支持有限,效果可能不如预期。

相关文章:

  • Godot开发2D冒险游戏——第三节:游戏地图绘制
  • 【Hive入门】Hive基础操作与SQL语法:DML操作全面解析
  • uniapp+vue3表格样式
  • 心磁图技术突破传统局限!心血管疾病早筛迈入“三零“新时代
  • 神经网络笔记 - 神经网络
  • 2025年大一ACM训练-搜索
  • VScode在 Markdown 编辑器中预览
  • 聊一聊接口测试的核心优势及价值
  • echarts自定义图表
  • AI与智能农业:如何通过精准农业提升作物产量与资源使用效率?
  • Linux进程学习【环境变量】进程优先级
  • AUTOSAR_Feature_Model_Analysis
  • c++流对象
  • 智慧水库与AI深度融合的实现方案及典型应用场景
  • MySQL快速入门篇---增删改查(下)
  • LeetCode 24 两两交换链表中的节点
  • 【深度好文】4、Milvus 存储设计深度解析
  • 【Nginx】负载均衡配置详解
  • 【2025最新Java面试八股】如何在Spring启动过程中做缓存预热?
  • kafka 中消费者 groupId 是什么
  • 见证上海援藏30年成果,萨迦非遗珍品展来沪
  • A股三大股指收跌:地产股领跌,银行股再度走强
  • 五一期间上海景观照明开启重大活动模式,外滩不展演光影秀
  • 民航局答澎湃:督促各单位进一步完善航班大面积延误和大面积备降应急处置预案
  • 金正恩出席朝鲜人民军海军驱逐舰入水仪式
  • 美联储官员:若特朗普高额关税致失业率飙升,将支持降息