1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565
|
import wave import requests import time import base64 from pyaudio import PyAudio, paInt16 import os from time import sleep import pyttsx3 from selenium import webdriver import pandas as pd import re from PIL import Image from wordcloud import WordCloud from imageio import imread import collections import matplotlib.pyplot as plt import pyecharts from sqlalchemy import create_engine
def spider_jinan(): js = "var q=document.documentElement.scrollTop=100000"
driver = webdriver.Chrome() driver.maximize_window()
url = 'https://www.tianqi.com/jinan/' driver.get(url) content = driver.page_source
cl = driver.find_elements_by_xpath("/html/body/div[5]/div/div[2]/div[1]/span[2]/a[2]/h3") cl[0].click()
list = driver.find_elements_by_xpath("/html/body/div[6]/div[2]/ul[1]") result = list[0].text.split("\n") driver.close() return result
def spider_res_jinan(result): weather = [] temp = [] data = [] month = [] day = [] a = 1 for i in result: a += 1 b = (a % 4)
if (b == 0): weather.append(i)
for i in result: lista = re.findall("\d{2}-\d{2}", i) tem = re.findall("\d{2}~\d{2}℃", i) if tem == []: del tem else: for iii in tem: temp.append(iii)
if lista == []: del lista else: for ii in lista: data.append(ii)
for i in data: month.append(i.split("-")[0]) day.append(i.split("-")[1])
return weather, temp, data, month, day
def mean_temp_jinan(temp): temp_mean = [] for i in temp: t = 0 z = re.findall("\d{2}", i) for ii in z: ii = int(ii) t += ii temp_mean.append(t / 2) return temp_mean
def image_jinan(weather): res = pd.Series() res["weather"] = pd.Series(weather) qq = pd.DataFrame({"天气": res["weather"]}) qq.to_csv("E:\\tianqi.txt", index=False)
stop = pd.read_csv('E:\\tianqi.txt', encoding='utf-8', engine='python', sep='limh')
back_pic = imread("E:\\code\\spider\\week8\\word_cloud\\helle.jpg") wc = WordCloud(font_path='C:\\Windows\\Fonts\\simkai.TTF', background_color="white", max_words=2000, mask=back_pic, max_font_size=200, random_state=42, collocations=True, )
tupian = Image.open("E:\\helle.jpg")
plt.figure(figsize=(16, 8)) plt.imshow(tupian) plt.axis('off')
def temp_to_csv(weather, temp, data): results = pd.DataFrame() res = pd.Series() res["weather"] = pd.Series(weather) res["temp"] = pd.Series(temp) res["data"] = pd.Series(data) results.insert(0, '天气', res["weather"]) results.insert(0, '温度', res["temp"]) results.insert(0, '日期', res["data"]) results.to_csv("E:\\weather.csv", index=False)
def plt_mean_temp_jinan(data, mean__temp): plt.xlabel("天气") plt.ylabel("平均温度") plt.title("温度变化") plt.plot(data, mean__temp) plt.grid(True) plt.show()
def plt_fer_weather(weather): tianqi = [] pinlv = [] word_counts = collections.Counter(weather) word_counts_top10 = word_counts.most_common(10) sun = 0 cloud = 0 lit_rain = 0 mit_rain = 0 sail = 0 shadom = 0 z_rain = 0 th_rain = 0 xiaoyu = 0 for i in word_counts_top10: print(i[0]) if i[0] == '多云': sun += 1 elif i[0] == '阴转雨': cloud += 1 elif i[0] == '多云转晴': lit_rain += 1 elif i[0] == '小雨到大雨': mit_rain += 1 elif i[0] == '中雨到大雨': shadom += 1 elif i[0] == '多云转雨': z_rain += 1 elif i[0] == '小雨到中雨': th_rain += 1 elif i[0] == '小雨转多云': sail += 1 elif i[0] == '小雨转阴': xiaoyu += 1 tianqi = ["小雨转阴", '小雨到大雨', '多云转晴', '小雨转多云', '多云', '小雨到中雨', '阴转雨', '中雨到大雨', '多云转雨'] pie = pyecharts.Pie("山东天气比例", '2020-7-11') pie.add('天气类型', tianqi, [xiaoyu, mit_rain, lit_rain, sail, sun, th_rain, cloud, shadom, z_rain], is_label_show=True)
pie = pyecharts.Pie("全国天气类型比例", '2018-4-16') pie.render('C:\\Users\\dupeibo\\Desktop\\未来30天天气概况.html')
def spider_shandong(): city = [] temp = [] weather = [] js = "var q=document.documentElement.scrollTop=100000"
driver = webdriver.Chrome() driver.maximize_window()
url = 'https://www.tianqi.com/province/shandong/' driver.get(url) content = driver.page_source
list = driver.find_elements_by_xpath("/html/body/div[7]/div[1]/div[5]/ul") result = list[0].text.split("\n") driver.close() return result
def shandong_data(result): city = [] temp = [] weather = [] max_temp = [] min_temp = [] a = 2 for i in result: a += 1 b = (a % 4)
if (b == 0): weather.append(i)
a = 3 for i in result: a += 1 b = (a % 4) if (b == 0): city.append(i)
for i in result: tem = re.findall('\d{2} ~ \d{2}℃', i) if tem == []: del tem else: for iii in tem: temp.append(iii)
for i in temp: t = 0 z = re.findall("\d{2}", i) min_temp.append(z[0]) max_temp.append(z[1]) return city, temp, weather, max_temp, min_temp
def shandong_Parallel(city, max_temp, min_temp): parallel = pyecharts.Parallel("高低温度的平行坐标系图", "2021-7-13", width=1200, height=600) parallel.config(city) parallel.add("高低温", [max_temp, min_temp], is_random=True)
parallel.render('C:\\Users\\dupeibo\\Desktop\\山东温度分析.html')
def jinan_to_sql(weather, temp, data): results = pd.DataFrame() res = pd.Series() res["weather"] = pd.Series(weather) res["temp"] = pd.Series(temp) res["data"] = pd.Series(data) results.insert(0, '天气', res["weather"]) results.insert(0, '温度', res["temp"]) results.insert(0, '日期', res["data"]) conn = create_engine('mysql+pymysql://root:dpb238031@localhost:3306/weather?charset=utf8') sql = 'select * from runoob_tbl' rub = pd.read_sql(sql, conn) results.to_sql(name='jinan_weather', con=conn, if_exists='append', index=True)
def shandong_to_sql(city, weather, min_temp, max_temp): results = pd.DataFrame() res = pd.Series() res["city"] = pd.Series(city) res["weather"] = pd.Series(weather) res["max_temp"] = pd.Series(max_temp) res["min_temp"] = pd.Series(min_temp) results.insert(0, '城市', res["city"]) results.insert(0, '天气', res["weather"]) results.insert(0, '最低温', res["min_temp"]) results.insert(0, '最高温', res["max_temp"]) conn = create_engine('mysql+pymysql://root:dpb238031@localhost:3306/weather?charset=utf8') results.to_sql(name='shandong_weather', con=conn, if_exists='append', index=False)
def audio(exam, weather, temp, month, day): if exam == "今天": pt = pyttsx3.init() pt.say("今天是:" + month[0] + "月" + day[1] + "日\n\n" + "今天的天气是\n" + weather[0] + "\n\n今天的气温是" + temp[0]) pt.runAndWait() elif exam == "明天": pt = pyttsx3.init() pt.say("明天是:" + month[1] + "月" + day[1] + "日\n\n" + "明天的天气是\n" + weather[1] + "\n\n明天的气温是" + temp[1]) pt.runAndWait() elif exam == "后天": pt = pyttsx3.init() pt.say("后天是:" + month[2] + "月" + day[1] + "日\n\n" + "后天的天气是\n" + weather[2] + "\n\n后天的气温是" + temp[2]) pt.runAndWait() elif exam == "大后天": pt = pyttsx3.init() pt.say("大后天是:" + month[3] + "月" + day[1] + "日\n\n" + "大后天的天气是\n" + weather[3] + "\n\n大后天的气温是" + temp[3]) pt.runAndWait()
framerate = 16000 num_samples = 2000 channels = 1 sampwidth = 2 FILEPATH = 'speech.wav'
base_url = "https://openapi.baidu.com/oauth/2.0/token?grant_type=client_credentials&client_id=%s&client_secret=%s" APIKey = "注册的APIKey" SecretKey = "注册的SecretKey"
HOST = base_url % (APIKey, SecretKey)
def getToken(host): res = requests.post(host) return res.json()['access_token']
def save_wave_file(filepath, data): wf = wave.open(filepath, 'wb') wf.setnchannels(channels) wf.setsampwidth(sampwidth) wf.setframerate(framerate) wf.writeframes(b''.join(data)) wf.close()
def my_record(): pa = PyAudio() stream = pa.open(format=paInt16, channels=channels, rate=framerate, input=True, frames_per_buffer=num_samples) my_buf = [] t = time.time() print('请讲话...')
while time.time() < t + 4: string_audio_data = stream.read(num_samples) my_buf.append(string_audio_data) print('录音结束.') save_wave_file(FILEPATH, my_buf) stream.close()
def get_audio(file): with open(file, 'rb') as f: data = f.read() return data
def speech2text(speech_data, token, dev_pid=1537): FORMAT = 'wav' RATE = '16000' CHANNEL = 1 CUID = '24422381' SPEECH = base64.b64encode(speech_data).decode('utf-8')
data = { 'format': FORMAT, 'rate': RATE, 'channel': CHANNEL, 'cuid': CUID, 'len': len(speech_data), 'speech': SPEECH, 'token': token, 'dev_pid': dev_pid } url = 'https://vop.baidu.com/server_api' headers = {'Content-Type': 'application/json'} print('正在识别...') r = requests.post(url, json=data, headers=headers) Result = r.json() if 'result' in Result: return Result['result'][0] else: return Result
if __name__ == '__main__': flag = '重新开始' while flag.lower() == '重新开始': print("您是要查看'济南天气'还是'山东所有城市的天气'?") pt = pyttsx3.init() pt.say("您是要查看济南天气还是山东所有城市的天气?") pt.runAndWait() sleep(2) my_record() TOKEN = getToken(HOST) speech = get_audio(FILEPATH) result = speech2text(speech, TOKEN, int(1536)) sleep(2) print("识别结果:" + result) print("开始收集数据....") sleep(2) if result == "济南天气": result = spider_jinan() weather, temp, data, month, day = spider_res_jinan(result) mean__temp = mean_temp_jinan(temp) print("目前有的功能\n\n查看最近天气\n查看未来30天的温度\n画出天气词云\n平均温度折线图\n保存数据\n查看未来天气类型\n将数据存入数据库\n\n请选择你要使用的功能") pt = pyttsx3.init() pt.say("\n\n\n\n\n\n\n目前有的功能\n\n查看最近天气\n查看未来30天的温度\n画出天气词云\n平均温度折线图\n保存数据\n查看未来天气类型\n将数据存入数据库\n\n请选择你要使用的功能") pt.runAndWait() my_record() TOKEN = getToken(HOST) speech = get_audio(FILEPATH) func = speech2text(speech, TOKEN, int(1536)) print("识别结果:" + func) sleep(2) if func == "查看最近天气": print("请输入要查看的信息,例如:今天,明天,后天,大后天") pt = pyttsx3.init() pt.say("请输入要查看的信息,例如:今天,明天,后天,大后天") pt.runAndWait() my_record() TOKEN = getToken(HOST) speech = get_audio(FILEPATH) apple = speech2text(speech, TOKEN, int(1536)) print("识别结果:" + apple) audio(apple, weather, temp, month, day) pt1 = pyttsx3.init() print("重新开始还是退出?") pt1.say("是否重新开始还是退出?") pt1.runAndWait() my_record() TOKEN = getToken(HOST) speech = get_audio(FILEPATH) flag = speech2text(speech, TOKEN, int(1536)) print("识别结果:" + flag) elif func == "查看未来三十天的温度": mean__temp = mean_temp_jinan(temp) plt_mean_temp_jinan(data, mean__temp) pt = pyttsx3.init() print("重新开始还是退出?") pt.say("是否重新开始还是退出?") pt.runAndWait() my_record() TOKEN = getToken(HOST) speech = get_audio(FILEPATH) flag = speech2text(speech, TOKEN, int(1536)) print("识别结果:" + flag) elif func == "画出天气词云": image_jinan(weather) pt = pyttsx3.init() print("重新开始还是退出?") pt.say("是否重新开始还是退出?") pt.runAndWait() my_record() TOKEN = getToken(HOST) speech = get_audio(FILEPATH) flag = speech2text(speech, TOKEN, int(1536)) print("识别结果:" + flag) elif func == "平均温度折线图": plt_mean_temp_jinan(data, mean__temp) pt = pyttsx3.init() print("重新开始还是退出?") pt.say("重新开始还是退出?") pt.runAndWait() my_record() TOKEN = getToken(HOST) speech = get_audio(FILEPATH) flag = speech2text(speech, TOKEN, int(1536)) print("识别结果:" + flag) elif func == "保存数据": temp_to_csv(weather, temp, data) pt = pyttsx3.init() print("重新开始还是退出?") pt.say("重新开始还是退出?") pt.runAndWait() my_record() TOKEN = getToken(HOST) speech = get_audio(FILEPATH) flag = speech2text(speech, TOKEN, int(1536)) print("识别结果:" + flag) elif func == "查看未来天气类型": plt_fer_weather(weather) os.system('C:\\Users\\dupeibo\\Desktop\\未来30天天气概况.html') pt = pyttsx3.init() print("重新开始还是退出?") pt.say("重新开始还是退出?") pt.runAndWait() my_record() TOKEN = getToken(HOST) speech = get_audio(FILEPATH) flag = speech2text(speech, TOKEN, int(1536)) print("识别结果:" + flag) elif func == "将数据存入数据库": jinan_to_sql(weather, temp, data) pt = pyttsx3.init() print("重新开始还是退出?") pt.say("数据库保存成功\n\n重新开始还是退出?") pt.runAndWait() my_record() TOKEN = getToken(HOST) speech = get_audio(FILEPATH) flag = speech2text(speech, TOKEN, int(1536)) print("识别结果:" + flag)
elif result == "山东所有城市的天气": result = spider_shandong() city, temp, weather, max_temp, min_temp = shandong_data(result) pt = pyttsx3.init() sleep(3) print("目前有的功能\n\n\n查看各城市天气状况\n将数据存入数据库") pt.say("目前有的功能\n\n\n查看各城市天气状况\n将数据存入数据库") pt.runAndWait() my_record() sleep(2) TOKEN = getToken(HOST) speech = get_audio(FILEPATH) fun2 = speech2text(speech, TOKEN, int(1536)) print("识别结果:" + fun2) if fun2 == "查看各城市天气状况": os.system("C:\\Users\\dupeibo\\Desktop\\山东温度分析.html") pt = pyttsx3.init() print("重新开始还是退出?") pt.say("重新开始还是退出?") pt.runAndWait() my_record() TOKEN = getToken(HOST) speech = get_audio(FILEPATH) flag = speech2text(speech, TOKEN, int(1536)) print("识别结果:" + flag) elif fun2 == "将数据存入数据库": shandong_to_sql(city, weather, min_temp, max_temp) pt = pyttsx3.init() print("重新开始还是退出?") pt.say("重新开始还是退出?") pt.runAndWait() my_record() TOKEN = getToken(HOST) speech = get_audio(FILEPATH) flag = speech2text(speech, TOKEN, int(1536)) print("识别结果:" + flag)
|