LoginSignup
3
6

More than 3 years have passed since last update.

PDFのコピペからGoogle翻訳のURLを開くPythonスクリプト

Last updated at Posted at 2021-02-03

はじめに

PDF の文章をコピペして Google 翻訳に入力すると文章の途中で改行が入って使いづらいので、コピペした文章内の改行を自動で削除し翻訳の結果を開く簡単なスクリプトを作成しました。

※ターミナル上で長文を表示すると見づらいので、 Google 翻訳の URL を Web ブラウザで開く様にしています。

動作確認した環境

Python 3.8.6

Python スクリプト

url_ggl_trans.py
import webbrowser

head='https://translate.google.co.jp/?sl=en&tl=ja&text=' # 言語の指定
term='&op=translate'
txt='start'
flag=0

while not flag:
    send=''
    print('Input sentences (if finish, press enter twice) -> ')
    while txt!='':
        txt=input()
        if txt == '':
            continue
        txt=' '.join(txt.split()) # 改行の削除
        send=send+txt+' '
    webbrowser.open(head+send+term) # 翻訳用 URL の表示
    if input('continue? (y/n) -> ') == 'n':
        flag = 1
    print()
    txt='start'

実行

クリップボードの文章をペーストして Enter を 2 回押すと翻訳ページが開かれます。

python url_ggl_trans.py
Input sentences (if finish, press enter twice) ->
(コピーした文章のペースト)

おわりに

今のままだと翻訳する毎にタブが増えていくので、既に Google 翻訳をブラウザで開いていたらページを更新するなどの機能を追加したいところです。

追記

Google 翻訳の URL に % などを入力すると別のコマンドとして解釈されてしまうようです。

Google の Translator モジュールを使ってターミナル上で表示すると特殊文字を良しなに扱ってくれるみたいなので、そのスクリプトも書いてみました。

Translator モジュールの導入はこちらの記事を参考にさせていただきました。

url_ggl_trans_v2.py
from googletrans import Translator

head='https://translate.google.co.jp/?sl=en&tl=ja&text='
term='&op=translate'
txt='start'
flag=0

while not flag:
    send=''
    print('Input sentences (if finish, press enter twice) -> ')
    while txt!='':
        txt=input()
        if txt == '':
            continue
        txt=' '.join(txt.split())
        send=send+txt+' '
    print(Translator().translate(text=send, src="en", dest="ja").text)
    if input('continue? (y/n) -> ') == 'n':
        flag = 1
    print()
    txt='start'

3
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
6