用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 的情感分析是基于英文语料库,可能对中文的支持有限,效果可能不如预期。