LoginSignup
3
0

More than 1 year has passed since last update.

Pythonでgoogletrans使用時の「AttributeError: 'NoneType' object has no attribute 'group'」解決方法

Posted at

1. やりたいこと

#visionをインポート
from google.cloud import vision
from googletrans import Translator

translator = Translator()

#image.jpgを開いて読み込む
with open('./image/image.jpg', 'rb') as image_file:
    content = image_file.read()

#visionAPIが扱える画像データにする
image = vision.Image(content=content)

#ImageAnnotatorClientのインスタンスを生成
annotator_client = vision.ImageAnnotatorClient()

response_data = annotator_client.label_detection(image=image)
labels = response_data.label_annotations

for label in labels:
    des = Translator().translate(label.description, src='en', dest='ja')
    print(des.text, ':', round(label.score * 100, 2), '%')

取得した画像をvisionAPIで画像認識し、出力されたラベルを自動で日本語に変換したい。
英語を日本語に変換するためにgoogleが提供しているgoogletransを使って実装していきたい。(googletransはGoogle Translate API を実装したPythonライブラリです)

2.問題点

AttributeError: 'NoneType' object has no attribute 'group'

Pythonでgoogletransを使って英語を日本語に変換したいのだが、「AttributeError: 'NoneType' object has no attribute 'group'」 が起きてしまった。
誤字脱字も確認したが、そのような形跡もないようだ。
開発したい機能ができないのでなんとか解決したい

3.解決方法

googletransのバージョンが問題だったようだ。
googletransをインストール済みだったので、まず下記のコマンドをターミナルに入力してアンインストールした。(筆者はWindows環境です)

pip uninstall googletrans

次に下記のコマンドで「googletrans==3.1.0a0」をインストールした。

pip install googletrans==3.1.0a0

4.結果

 : 98.47 %
笑顔 : 97.43 %
 : 96.62 %
表情 : 93.29 %
人間 : 89.59 %
ギターアクセサリー : 88.6 %
あご : 87.69 %
ハッピー : 87.13 %
ジェスチャー : 85.26 %
タータン : 84.28 %

問題なく出力できたようだ。

まとめ

今回はgoogletransのバージョンが問題でした。
コードみてもリファレンスみてもわからないときは、バージョンを疑うべきですね。
今後の教訓です。

3
0
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
0