こんな方におすすめ
- webスクレイピングしてどんなことができるか知りたい
- google-text-to-speechを使ってみたい
自分のブログサイトをスクレイピングしてオススメ情報と新着情報を音声でアナウンスするプログラムを作成します。以前、紹介したWEBスクレイピングからツイッターへと、Google text to speechをPythonで実行を組み合わせてちょっと変更するだけです。
プログラムはそういう意味でも資産です。
A+B=C、C+D=Eというように、組み合わせるだけで様々なプログラムが作成することができます。
作成したプログラムは管理しておきましょう。
google-text-to-speechは、初期設定が必要です。初期設定を終えていない方は,Google text to speechをPythonで実行を参考にして設定してください。
プログラムの内容
以下のように、必要なPythonモジュールをインポートします。
1 2 3 4 5 6 7 |
import requests from bs4 import BeautifulSoup import tweepy import time from google.cloud import texttospeech from pygame import mixer |
スクレイピングするurlを入力します。今回は私のブログです。笑
1 2 3 |
target_url = "https://mayrsblog.com" r = requests.get(target_url) soup = BeautifulSoup(r.text, "html.parser") |
soupからfind_allメソッドを用いて、<h 5>タグの中身をスクレイピングする。このタグに、オススメ情報と新着情報のタイトルが入力させるためです。
1 |
elems = soup.find_all(["h5"]) |
スクレイピングした文章を加工して、google-text-to-speechに読み込ませるための文章を作成します。
1 2 3 4 5 6 7 8 |
count=0 message_stack = "" message_stack+="まずはブログのおすすめ情報だよ!" for e in elems: message_stack +=e.getText() if(count==3): message_stack+="次はブログの新着情報だよ!" count=count+1 |
テキストを音声に変換し再生する関数を作成します。message:音声に変換したいテキストを入れます。
language_codeは音声変換する言語を入れます。今回は日本語にしてます。
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 |
def voice_from_text(message): # Instantiates a client client = texttospeech.TextToSpeechClient() # Set the text input to be synthesized synthesis_input = texttospeech.types.SynthesisInput(text=message) # Build the voice request, select the language code ("en-US") and the ssml # voice gender ("neutral") voice = texttospeech.types.VoiceSelectionParams( language_code='ja-JP', ssml_gender=texttospeech.enums.SsmlVoiceGender.NEUTRAL) # Select the type of audio file you want returned audio_config = texttospeech.types.AudioConfig( audio_encoding=texttospeech.enums.AudioEncoding.MP3) # Perform the text-to-speech requeston the text input with the selected # voice parameters and audio file type response = client.synthesize_speech(synthesis_input, voice, audio_config) # The response's audio_content is binary. with open('output.mp3', 'wb') as out: # Write the response to the output file. out.write(response.audio_content) print('Audio content written to file "output.mp3"') #ここから音声再生のプログラム mixer.init() #初期化 mixer.music.load("output.mp3") mixer.music.play(1) |
スクレイピングして作成した文章を、voice_from_textの関数で再生します。
1 |
voice_from_text(message_stack) |
次のようなMP3ファイルが作成され、音声が再生されます。
まとめ
今回は、webスクレイピングした情報を音声変換して読ませるプログラムを作りました。以前に紹介したプログラムを組み合わせただけで作れました。このプログラムの応用としては、ツイッターをスクレイピングして音声変換であったり、英語の覚えたい文章をランダムに流すとか色々可能です。
ぜひトライしてみてください。