1
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?

More than 1 year has passed since last update.

副反応疑い報告状況についてのPDFをCSVに変換

Posted at

予防接種法に基づく医療機関からの副反応疑い報告状況について(コミナティ筋注・報告症例一覧) (PDF:5,092KB)
https://www.mhlw.go.jp/content/10601000/000853766.pdf

pdfplumberでテーブルを抽出しようとすると表の最後に線がないため最終行が取得できない
index.png

縦線の下の位置を取得して最終の横線を追加
index1.png

縦線を追加
index2.png

テーブル確認
index4.png

PDFダウンロード

!wget https://www.mhlw.go.jp/content/10601000/000853766.pdf -O data.pdf

プログラム

import pdfplumber
import pandas as pd

from tqdm.notebook import tqdm

with pdfplumber.open("data.pdf") as pdf:

    dfs = []

    for page in tqdm(pdf.pages[1:]):

        # 縦線
        vertical = [
            edge["x0"]
            for edge in page.debug_tablefinder().edges
            if edge["orientation"] == "v"
        ]

        # 縦線の一番下の位置
        bottom = max(
            [
                edge["bottom"]
                for edge in page.debug_tablefinder().edges
                if edge["orientation"] == "v"
            ]
        )

        # 横線
        horizontal = [
            edge["top"]
            for edge in page.debug_tablefinder().edges
            if edge["orientation"] == "h"
        ]

        # 横線に縦線の一番下の位置を追加
        horizontal.append(bottom)

        table_settings = {
            "vertical_strategy": "explicit",
            "explicit_vertical_lines": vertical,
            "horizontal_strategy": "explicit",
            "explicit_horizontal_lines": horizontal,
            "snap_tolerance": 3,
            "intersection_tolerance": 3,
        }

        table = page.extract_table(table_settings)

        df_tmp = pd.DataFrame(table)

        dfs.append(df_tmp)

df = pd.concat(dfs)

df.shape

df.to_csv("result.csv", encoding="utf_8_sig")
1
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
1
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?