• Skip to main content
  • Skip to primary sidebar

学習記録

python3

翻訳ツールGoogleトランスの代わり

2023年1月4日 by 河副 太智 Leave a Comment

Googleトランスがなぜか使えないので大体ツールを使用

1
pip install deep-translator

でdeeptranslatorをインストール

1
2
3
4
from deep_translator import GoogleTranslator
translated = GoogleTranslator(source='auto',target='en').translate("요소로")
 
print(translated)

>>as an element

Filed Under: python3

PDFファイル操作

2022年11月26日 by 河副 太智 Leave a Comment

PDFの文字列をテキストに

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
from pdfminer.pdfinterp import PDFResourceManager
from pdfminer.converter import TextConverter
from pdfminer.pdfinterp import PDFPageInterpreter
from pdfminer.pdfpage import PDFPage
from pdfminer.layout import LAParams
from io import StringIO
 
# 標準組込み関数open()でモード指定をbinaryでFileオブジェクトを取得
fp = open("files/Training-Manual-for-Harmonized-Tariff-Schedule-Hts-Classification.pdf", 'rb')
 
# 出力先をPythonコンソールするためにIOストリームを取得
outfp = StringIO()
 
 
# 各種テキスト抽出に必要なPdfminer.sixのオブジェクトを取得する処理
 
rmgr = PDFResourceManager() # PDFResourceManagerオブジェクトの取得
lprms = LAParams()          # LAParamsオブジェクトの取得
device = TextConverter(rmgr, outfp, laparams=lprms)    # TextConverterオブジェクトの取得
iprtr = PDFPageInterpreter(rmgr, device) # PDFPageInterpreterオブジェクトの取得
 
# PDFファイルから1ページずつ解析(テキスト抽出)処理する
for page in PDFPage.get_pages(fp):
    iprtr.process_page(page)
 
text = outfp.getvalue()  # Pythonコンソールへの出力内容を取得
 
outfp.close()  # I/Oストリームを閉じる
device.close() # TextConverterオブジェクトの解放
fp.close()     #  Fileストリームを閉じる
 
print(text)  # Jupyterの出力ボックスに表示する

PDFの表をエクセルに変換

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# Import Module
import os
import tabula
import pandas as pd
 
filename= "files/Seniority List 2018 19.pdf"
  
#pdfのページ数を取得
amount = (len(tabula.read_pdf(filename, pages = 'all')))
 
#pdfのページ数だけまわす
for i in range(amount):
    df = tabula.read_pdf(filename, pages = 'all')[i]
    ### Convert into Excel File
    df.to_excel('files/excel' + str(i) + '.xlsx')
    
#アウトプットされたファイルの名前をリストに入れる    
filename= "excel"
filelist = os.listdir("files")
filelist = [f for f in filelist if filename in f]
 
 
 
# エクセルを一つずつpandasデータとして取得
each_file = []
for file in range(len(filelist)):
    #エクセルファイルの数だけforを回し、それぞれをリスト変数に入れていく
    each_file.append(pd.read_excel('files/excel' + str(file) + '.xlsx', header=None))
 
#リストを結合
df = pd.concat(each_file)
df.to_excel('files/total.xlsx', index=False)

PDFの画像を抽出

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# PRG1:ライブラリ設定
import fitz
import os
# PRG2:画像の保存先フォルダを設定
filename = 'files/dai1.pdf'
dir_name = filename.split('.')[0]
img_dir = os.path.join(os.getcwd(),dir_name)
if os.path.isdir(img_dir) == False:
    os.mkdir(img_dir)
# PRG3:PDFファイルを読み込む
doc = fitz.open(filename)
# PRG4:画像情報を格納するリストを作成
images = []
# PRG5:1ページずつ画像データを取得
for page in range(len(doc)):
    images.append(doc[page].get_images())
# PRG6:ページ内の画像情報を順番に処理
for pageNo, image in enumerate(images):
    # PRG7:ページ内の画像情報を処理する
    if image != []:
        for i in range(len(image)):
            # PRG8:画像情報の取得
            xref = image[i][0]
            smask = image[i][1]
            if image[i][8] == 'FlateDecode':
                ext = 'png'
            elif image[i][8] == 'DCTDecode':
                ext = 'jpeg'
            # PRG9:マスク情報の取得と画像の再構築
            pix = fitz.Pixmap(doc.extract_image(xref)["image"])
            if smask > 0:
                mask = fitz.Pixmap(doc.extract_image(smask)["image"])
                pix = fitz.Pixmap(pix, 0)
                pix = fitz.Pixmap(pix, mask)
            # PRG10:画像を保存
            img_name = os.path.join(img_dir, f'image{pageNo+1}_{i}.{ext}')
            pix.save(img_name)

 

Filed Under: python3

Googleトランスで翻訳

2022年9月1日 by 河副 太智 Leave a Comment

Googleトランスにおいては謎のエラーが発生してうまく動かなかったが、
google_trans_newを使用してから翻訳できるようになった。

①pip install google-trans-new
でインストール

➁C:\Users\xxx\AppData\Local\Programs\Python\Python310\Lib\site-packages\google_trans_newを開く

enter image description here

③151行目のresponse = (decoded_line + ‘]’) を
response = decoded_lineに変える

④以下のコードを実行

1
2
3
4
from google_trans_new import google_translator
translator = google_translator()  
translate_text = translator.translate('요소로',lang_tgt='en')
print(translate_text)

これでgoogle翻訳が使用可能になった2022/9/1現在

Filed Under: python3, スクレイピング

タイムアウトでリトライ

2020年3月18日 by 河副 太智 Leave a Comment

タイムアウトでリトライ

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
i = 0
while i < 20:
    try:
        driver.get("https://unipass.customs.go.kr/clip/index.do")
        print("成功")
 
    except TimeoutException:
        i = i + 1
        print("Timeout, Retrying... (%(i)s/%(max)s)")
        continue
 
    else:
        i = i + 1
        print("その他, Retrying...")
        continue

 

Filed Under: python3

forのエラー処理

2020年1月19日 by 河副 太智 Leave a Comment

forでのエラー発生時の処理

1
2
3
4
5
6
7
8
for i in range(x):
    try:
        trans_en = translator.translate( df["名称"][i], dest='ja')
        print(i)
        df["名称"][i] = trans_en.text
    except:
        time.sleep(600)
        pass

googletransの使い過ぎでエラーになるので、エラーが出たら10分休む設定

Filed Under: python3

WEBアプリをエックスサーバー

2020年1月11日 by 河副 太智 Leave a Comment

エックスサーバーでPythonを動かす方法

まずは、公開ディレクトリ以下に適当にPython用のフォルダを作成し、「.htaccess」という名前のファイルを新規作成する。

ファイルの中身は下記。
※必ず改行コード「LF」で保存すること。

1
AddHandler cgi-script .py

この設定を追加することで、拡張子「.py」のファイルがcgi(webプログラムを実行しその結果を表示するもの)として実行される。

 

「.htaccess」と同じディレクトリに「test.py」を作成する。

ファイルの中身は下記。
※必ず改行コード「LF」で保存すること。

1
2
3
#!/usr/bin/python3
print("Content-type: text/html\n\n")
print("hello,world")

1行目は、cgiプログラムを書くときに記載するもので、pythonのパスを指定する。

エックスサーバーでは、python2系と3系がデフォルトで利用でき、「/usr/bin/python3」とするとpython3系を使う。

2行目は、ブラウザにテキストを表示しさせるための命令。HTMLのヘッダーとなる。

↑conversion.pyというのがメインのコードを記述したファイル

Filed Under: webアプリ

  • Page 1
  • Page 2
  • Page 3
  • Interim pages omitted …
  • Page 12
  • Go to Next Page »

Primary Sidebar

カテゴリー

  • AWS
  • Bootstrap
  • Dash
  • Django
  • flask
  • GIT(sourcetree)
  • Plotly/Dash
  • VPS
  • その他tool
  • ブログ
  • プログラミング
    • Bokeh
    • css
    • HoloViews
    • Jupyter
    • Numpy
    • Pandas
    • PosgreSQL
    • Python 基本
    • python3
      • webアプリ
    • python3解説
    • scikit-learn
    • scipy
    • vps
    • Wordpress
    • グラフ
    • コマンド
    • スクレイピング
    • チートシート
    • データクレンジング
    • ブロックチェーン
    • 作成実績
    • 時系列分析
    • 機械学習
      • 分析手法
      • 教師有り
    • 異常値検知
    • 自然言語処理
  • 一太郎
  • 数学
    • sympy
      • 対数関数(log)
      • 累乗根(n乗根)
    • 暗号学

Copyright © 2025 · Genesis Sample on Genesis Framework · WordPress · Log in