ファイル名:speakWeather.py
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 | # -*- coding: utf-8 -*- import urllib.request from bs4 import BeautifulSoup import re # 喋らせる準備(WindowsAPIの機能を使う) import win32com.client as wincl # pip install pywin32 voice = wincl.Dispatch( "SAPI.SpVoice" ) """ お天気情報をサイトから取得する """ # Yahoo!のページから水戸の天気を開く url = "https://weather.yahoo.co.jp/weather/jp/8/4010.html" data = urllib.request.urlopen(url) # HTMLを解析して取得 soup = BeautifulSoup(data, 'html.parser' ) # classが 'forecastCity' のタグを取得 tenkiAll = soup.find( class_ = "forecastCity" ) date = tenkiAll.find( class_ = "date" ) tenki = tenkiAll.find( class_ = "pict" ) high = tenkiAll.find( class_ = "high" ) low = tenkiAll.find( class_ = "low" ) """ 画面に出力 """ print ( "{}" . format (date.text)) print ( "{}" . format (tenki.text)) print ( "最高気温: {}" . format (high.text)) print ( "最低気温: {}" . format (low.text)) """ 天気をしゃべらせる """ # 先頭の気温(数値)のみ取り出す正規表現 regexp = re. compile ( "^[0-9]+" ) # 最高気温と最低気温を取り出す high = regexp.search(high.text) low = regexp.search(low.text) # 文章にしてしゃべらせる voice.Speak(date.text) voice.Speak(tenki.text) voice.Speak( "最高気温は" + high[ 0 ] + "度" ) voice.Speak( "最低気温は" + low[ 0 ] + "度" ) |
コメント