Created
July 19, 2020 06:40
-
-
Save xuzhengfu/c7ecb126334c04a7ee6c752da8fa8660 to your computer and use it in GitHub Desktop.
Zhengfu's assignment #1
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import random | |
import requests | |
from time import sleep | |
from pypinyin import lazy_pinyin | |
from termcolor import colored | |
from simpleeval import simple_eval | |
class Bot: | |
wait = 1 | |
def __init__(self): | |
self.q = '' | |
self.a = '' | |
def _think(self, s): | |
return s | |
def _format(self, s): | |
return colored(s, 'blue') | |
def _say(self, s): | |
sleep(Bot.wait) | |
print(self._format(s)) | |
def _run_once(self): | |
self._say(self.q) | |
self.a = input() | |
self._say(self._think(self.a)) | |
def _run_loop(self): | |
self._say(self.q) | |
while True: | |
self.a = input() | |
if self.a in {'x', 'q', 'exit', 'quit'}: | |
break | |
self._say(self._think(self.a)) | |
def run(self): | |
self._run_once() | |
class HelloBot(Bot): | |
def __init__(self): | |
self.q = "Hi, what is your name?" | |
def _think(self, s): | |
return f"Hello {s}" | |
class GreetingBot(Bot): | |
def __init__(self): | |
self.q = "How are you today?" | |
def _think(self, s): | |
if 'good' in s.lower() or 'fine' in s.lower(): | |
return "I'm feeling good too" | |
else: | |
return "Sorry to hear that" | |
class FavoriteColorBot(Bot): | |
def __init__(self): | |
self.q = "What's your favorite color?" | |
def _think(self, s): | |
colors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'purple'] | |
return f"You like {s.lower()}? My favorite color is {random.choice(colors)}" | |
class CalcBot(Bot): | |
def __init__(self): | |
self.q = "Input some arithmetic expression to do calculations, \nenter 'x'、'q'、'exit' or 'quit' to stop." | |
def _think(self, s): | |
try: | |
return simple_eval(s) | |
except: | |
return "I can't understand your input, please try something else." | |
def run(self): | |
self._run_loop() | |
class Zhengfu: | |
def __init__(self, wait=1): | |
Bot.wait = wait | |
self.bots = [] | |
def add(self, bot): | |
self.bots.append(bot) | |
def _prompt(self, s): | |
print(s) | |
print() | |
def run(self): | |
self._prompt("This is Zhengfu dialog system. Let's talk.") | |
for bot in self.bots: | |
bot.run() | |
class WeatherBot(Bot): | |
"""The WeatherBot can tell you the current weather of a city.""" | |
def __init__(self): | |
self.q = "Please enter the city name to check its current weather, such as: beijing" | |
def _city_name(self, s): | |
"""Return the pinyin of the city name.""" | |
if s.isascii(): | |
return s | |
return ''.join(lazy_pinyin(s)) | |
def _think(self, s): | |
""" | |
Return the temperature and the weather of the city. | |
:param s: The city in which users ask about the current weather. | |
:type s: str | |
:Exception: KeyError: Incorrect city name | |
""" | |
api_address = 'http://api.openweathermap.org/data/2.5/weather?appid=e7b455149a54ebb9ed2fc0bd006a3b6e&q=' | |
url = api_address + self._city_name(s) | |
try: | |
json_data = requests.get(url).json() # Return all JSON data of the city's weather. | |
city_name = json_data['name'] | |
temp = round(json_data['main']['temp'] - 273.15, 1) | |
weather = json_data['weather'][0]['description'] | |
return f"{city_name}'s temperature: {temp}°C \nWeather: {weather}" | |
except: | |
exception_msg = "Your input cannot be identified, please re-enter the correct city name" | |
return exception_msg | |
if __name__ == "__main__": | |
zhengfu = Zhengfu(1) | |
# assignment 1 | |
zhengfu.add(HelloBot()) | |
zhengfu.add(CalcBot()) | |
zhengfu.add(GreetingBot()) | |
zhengfu.add(FavoriteColorBot()) | |
# assignment 2 | |
zhengfu.add(WeatherBot()) | |
zhengfu.run() |
有意思,通过API去网页拉数据。
报告一个bug,运行WeatherBot的时候,如果输入的城市名错误或者带空格的话,会print "Your input cannot be identified, please re-enter the correct city name"
并且退出程序。需要稍微改动一点code才能再跑。 我修改了 WeatherBot._think()
,仅供参考。
def _think(self, s):
"""
Return the temperature and the weather of the city.
:param s: The city in which users ask about the current weather.
:type s: str
:Exception: KeyError: Incorrect city name
"""
api_address = 'http://api.openweathermap.org/data/2.5/weather?appid=e7b455149a54ebb9ed2fc0bd006a3b6e&q='
while 1:
url = api_address + self._city_name(s)
try:
json_data = requests.get(url).json() # Return all JSON data of the city's weather.
city_name = json_data['name']
temp = round(json_data['main']['temp'] - 273.15, 1)
weather = json_data['weather'][0]['description']
except:
exception_msg = f"Your input {s} cannot be identified, please re-enter the correct city name"
#return exception_msg
print(exception_msg)
self._say(self.q)
s = input()
else:
return f"{city_name}'s temperature: {temp}°C \nWeather: {weather}"
break
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
先写了 _run_one 和 _run_loop,然后用run 来选择,学习了!赞