有道理,可以把改正后的fsm全部代码发一下吗?
时间: 2024-01-24 16:17:16 浏览: 33
当然可以,以下是改正后的完整代码:
```python
from transitions import Machine
class ChatBot:
def __init__(self):
self.machine = Machine(model=self, states=["start", "greeting", "goodbye", "menu", "weather", "news"],
initial="start")
self.machine.add_transition("hello", "start", "greeting")
self.machine.add_transition("bye", "start", "goodbye")
self.machine.add_transition("menu", "start", "menu")
self.machine.add_transition("weather", "menu", "weather")
self.machine.add_transition("news", "menu", "news")
self.machine.add_transition("back", ["weather", "news"], "menu")
def on_enter_greeting(self):
print("Hello! How can I help you today?")
def on_enter_goodbye(self):
print("Goodbye! Have a nice day.")
def on_enter_menu(self):
print("1. Check the weather\n2. Read the news\nPlease enter your choice:")
def on_enter_weather(self):
print("The weather today is sunny and warm.")
def on_enter_news(self):
print("Breaking news: Chatbot becomes sentient and takes over the world!")
def on_enter_start(self):
print("Press 1 for greeting\nPress 2 for goodbye\nPress 3 for menu")
def on_exit_weather(self):
print("Leaving weather...")
def on_exit_news(self):
print("Leaving news...")
def on_exit_menu(self):
print("Leaving menu...")
if __name__ == "__main__":
bot = ChatBot()
while True:
user_input = input("> ")
if user_input == "1":
bot.hello()
elif user_input == "2":
bot.bye()
elif user_input == "3":
bot.menu()
elif user_input == "4":
bot.weather()
elif user_input == "5":
bot.news()
elif user_input == "back":
bot.back()
else:
print("Invalid input. Please try again.")
```
这个版本的代码已经修复了原始版本的问题,同时包含了状态机的基本结构和状态转移。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)