0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Amazonの適格請求書を一気に読み込んでCSVファイルにする

Posted at

Amazonの適格請求書(PDF)から一部を抜き出す方法

目的

Amazonの適格請求書(PDF)から、登録番号と合計金額を取り出してCSVファイルに変換したかったので、調べてpythonコードを作成しました。

前準備

pypdfが必要です。以下のコマンドでインストールします。

pip install pypdf

amazonの請求書は、xxx_Amazon_invoice.pdfという名前にしておきます。xxxは連番や商品名です。

コード

コードは以下になります。convert.pyなどのファイル名で保存してください。

import pypdf
import pandas as pd
from tqdm import tqdm
import glob

pdf_files = glob.glob("*Amazon_invoice.pdf")
F = []
T = []
P = []

for pdf_file in tqdm(pdf_files):
    reader = pypdf.PdfReader(pdf_file)
    F.append(pdf_file)
    T.append("")
    P.append("")
    for e in tqdm(reader.pages):
        txt = e.extract_text()
        for v in txt.split("\n"):
            if "登録番号" in v :
                v = v.split()[-1]
                T[-1] = v
            if "合計" in v :
                v = v.split()
                if len(v) > 3:
                    v = v[3].replace("合計", "") 
                    P[-1] = v[1:]


df = pd.DataFrame()
df["請求書ファイル名"]=F
df["登録番号"]=T
df["合計金額"]=P

df.to_csv("output.csv", index=False)
print(df)

実行

以下のように実行するとoutput.csvを作成します。

python3 convert.py

中身は、以下のようになります。

output.csv
請求書ファイル名,登録番号,合計金額
001_Amazon_invoice.pdf,Txxxxxxxxxxxxx,"29,800"
002_Amazon_invoice.pdf,Txxxxxxxxxxxxx,"5,292"
003_Amazon_invoice.pdf,Txxxxxxxxxxxxx,"2,090"

注意事項

アマゾンのinvoiceのフォーマットが変更された場合は修正が必要となります。以下の部分が、登録番号と合計を取り出している部分なので、ここを修正してください。

        txt = e.extract_text()
        for v in txt.split("\n"):
            if "登録番号" in v :
                v = v.split()[-1]
                T[-1] = v
            if "合計" in v :
                v = v.split()
                if len(v) > 3:
                    v = v[3].replace("合計", "") 
                    P[-1] = v[1:]
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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?