LoginSignup
0
0

More than 1 year has passed since last update.

pythonのライブラリにある関数の説明を日本語で見る

Last updated at Posted at 2021-08-28

pythonのライブラリにある関数の説明を日本語で見る

pythonのライブラリにある関数の説明を日本語で見れるようにするための関数を作ってみました。手順としては次の3段階です。

1. ライブラリの関数が入っているpythonコードにアクセス。
2. 関数の説明部分だけ引っ張り出す。
3. google翻訳を使って翻訳

ライブラリとしては、sysとgoogle翻訳を使うためにgoogletransを使います。

ライブラリの関数が入っている場所はpythonのフォルダのあるところなので、そこはsys.pathで確認できます。

google翻訳のライブラリは、普通にpip install googletransとやっても実行時にエラーが出ることがでるので、下記リンクを参考に

pip install googletrans==4.0.0-rc1

でインストールしました。

プログラムは下記になります。
たとえば、numpyで逆行列を計算するnumpy.linalg.invの説明を見たいときはgetfuncinfo("numpy.linalg.inv")で呼び出します。

import sys
from googletrans import Translator

def getfuncinfo(tarfunc):
    tarfuncs=tarfunc.split(".")

    #フォルダ名はsys.pathで出てくる3番目のものがpythonのフォルダまでを示したものだったのでそれを使う
    f=open(sys.path[2]+"/site-packages/"+tarfuncs[0]+"/"+tarfuncs[1]+"/"+tarfuncs[1]+".py")
    funcn=tarfuncs[2]

    #ここで.pyファイルから指定の関数を定義している範囲だけ取り出す
    lines=f.read()
    posi = lines.find("def "+funcn+"(")
    if posi<0:
        posi = lines.find("def "+funcn+" (")
    lines1=lines[posi:]

    posi2=lines1[10:].find("def ")
    lines2=lines1[:posi2]
    #関数のあと"""で囲われた部分が関数の説明になるので、その範囲の文章を取り出してgoogle翻訳で翻訳する
    if lines2.find('"""')>=0:
        funcd=lines2.split('"""')[1]
        jfuncd=entoja(funcd)
        return(jfuncd)   

#google翻訳を使って日本語に翻訳
def entoja(lines):
    translator = Translator()
    translated = translator.translate(lines, dest="ja");
    return(translated.text)

tarfunc="numpy.linalg.inv"
jfuncd=getfuncinfo(tarfunc)
print(jfuncd)

linalgの関数のありかが下記であることがわかったため上記のプログラムで取り出せました。

/python3.8/site-packages/numpy/linalg/linalg.py

フォルダをかまさない他の関数などはどこにアクセスするかなどおいおい調べながら更新していきます。どのファイルにアクセスされているかなどの知識が不十分なので、アドバイスなどコメントでいただけると、適宜改善しながら更新していきます。

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