【Cloud9】Jupyter Notebook環境をnumpy簡単にセットアップ
みるみる
インフラエンジニアめも
そんな方法を知りたくはないでしょうか?
この記事では、Pythonのseleniumを使用して、準備したテキストファイルを読み込みGoogle翻訳を自動的に実行する方法を紹介します。
Google翻訳を自動化する前に事前に準備が必要です。
Google Chrome Driverをダウンロードする。
※ダウンロードするファイルについては、ご自身のChoromeのバージョンを確認してください。
https://chromedriver.chromium.org/downloads
pythonのライブラリを導入
pip install beautifulsoup4 pip install selenium
Google翻訳自動化のPythonスクリプトをコピーして、『Google_Translate.py』という名前で保存します。
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from bs4 import BeautifulSoup
import urllib.parse
import csv
import time
import os
class Translator:
def __init__(self):
self.options = Options()
self.options.add_argument('--headless')
self.browser = webdriver.Chrome(chrome_driver)
self.browser.implicitly_wait(3)
def translate(self, text, dest='ja'):
# 翻訳したい文をURLに埋め込んでからアクセスする
text_for_url = urllib.parse.quote_plus(text, safe='')
url = "https://translate.google.co.jp/#ja/en/{0}".format(text_for_url)
self.browser.get(url)
# # 2秒待機する
time.sleep(2)
# 翻訳結果を抽出する
ja = BeautifulSoup(self.browser.page_source, "html.parser") \
.find(class_="tlid-translation translation")
return ja.text
def quit(self):
self.browser.quit()
#スクリプトを実行するパスを指定
base_path = os.path.dirname(os.path.abspath(__file__))
#スクリプト実行するフォルダと同じ階層にchrome driverを配置している前提
chrome_driver = base_path + '/chromedriver.exe'
input_file = base_path + '/input.in'
output_file = base_path + '/output.log'
#インスタンス化
translator = Translator()
#書き込み用の配列作成
result_write=[]
#インプットファイルを読み込み
with open(input_file, mode='rt', encoding='shift-jis') as f:
for line in f:
#改行を削除して、1文字づつになるようにする
line=line.rstrip('\n')
print(line)
ja = translator.translate(line.rstrip('\n'))
print(ja)
result_write.append(ja)
#ファイルを閉じる・処理を終える
f.close()
translator.quit()
#変換したファイルの書き込み
with open(output_file, 'wt') as outfile:
for ele in result_write:
outfile.write(ele+'\n')
outfile.close()
Pythonを実行するフォルダ構成は以下のような感じです。

Google翻訳したいテキストファイルを拡張子が【.ini】ファイルを作成します。

機械言語処理 私はプログラミング勉強中です。 みんなでPython学習頑張りましょう。

Pythonスクリプトを実行後は、output.logというファイルが作成されます。
Google翻訳の結果は以下となります。

Pythonを勉強すると、日々の作業が自動化できるので、おススメです。
プログラミングを勉強したいけど、どのようなことをしたいか悩むことも多くあると思います。
そんな場合は、一度、自分がプログラミングでどのようなことがしたいのか相談をする場に行くのもいいです。