--Scraping the entered word from the translation site and displaying the translation result --Outputs audio files at the same time as translation --Save the audio file with the word name .mp3
The libraries used are as follows.
Library | Use |
---|---|
os | Check the path |
requests | Get html, download mp3 |
bs4 | html analysis |
tkinter | Creating a GUI |
pygame | Play mp3 |
random | Exception handling |
import os
import random
import tkinter
import requests
from bs4 import BeautifulSoup
from pygame import mixer
class Translation:
def __init__(self):
self.root = tkinter.Tk()
self.root.title('Translation')
self.root.geometry('500x200')
self.root.attributes('-topmost', True)
self.text_box = tkinter.Entry(width=20, font=('', 20), justify='center')
self.text_box.focus_set()
self.text_box.pack()
self.root.bind('<Return>', self.scraping)
self.root.bind('<space>', self.delete)
self.answer = tkinter.Message(self.root, text='', font=('', 20), width=450)
self.answer.pack(anchor='center', expand=1)
self.root.mainloop()
def scraping(self, event): #Scraping
try:
res = requests.get('https://ejje.weblio.jp/content/' + self.text_box.get())
soup = BeautifulSoup(res.content, 'html.parser')
txt = soup.find('td', {'class': 'content-explanation ej'})
self.answer['text'] = txt.text
self.sound(soup)
except:
self.answer['text'] = random.choice(('(^^;)?', '(・ Ω ・)?', "('Д')?", '(;・`д ・ ´)?'))
def sound(self, soup): #Download and play mp3
mp3_directory_path = 'd:/python/Application/mp3/' #mp3 save destination
if not os.path.exists(mp3_directory_path):
os.mkdir(mp3_directory_path)
if os.path.exists(mp3_directory_path + self.text_box.get() + '.mp3'):
pass
else:
audio = soup.find('audio', {'class': 'contentAudio'})
src = audio.find('source')['src']
res = requests.get(src, stream=True)
with open(mp3_directory_path + self.text_box.get() + '.mp3', 'wb') as f:
f.write(res.content)
mixer.init()
mixer.music.load(mp3_directory_path + self.text_box.get() + '.mp3')
mixer.music.play()
def delete(self, event): #Delete all characters in the input field with the space key
self.text_box.delete(0, tkinter.END)
Translation()
I managed to get it into shape. The Qiita article made by another person was very helpful. After that, if you create a bat file on your desktop, you can easily launch it. You may also be able to create word listening tests from downloaded mp3 files.
Recommended Posts