Gab*_*uto 4 python ghostscript pdf-extraction python-camelot
我正在尝试使用camelot从此pdf链接中提取表格,但是,当尝试以下代码时:
import camelot
file = 'relacao_medicamentos_rename_2020.pdf'
tables = camelot.read_pdf(file)
tables.export('relacao_medicamentos_rename_2020.csv', f='csv', compress=False)
Run Code Online (Sandbox Code Playgroud)
简单什么都不会发生。这很奇怪,因为当我尝试相同的代码但使用此 pdf链接时效果非常好。
ros*_* b. 10
正如Stefano建议的那样,您需要指定相关页面并设置选项flavor=\'stream\'。仅当单元格flavor=\'lattice\'之间有线条时,默认设置才有效。
此外,增加row_tol有助于将行分组在一起。例如,第一个表的标题不会被读取为三个单独的行,而是作为一行。具体而言,“Concentra\xc3\xa7\xc3\xa3o/Composi\xc3\xa7\xc3\xa3o\”被识别为连贯文本。
您也可能想使用strip_text=\'\\n\'删除换行符。
结果是(以第 17 和 18 页为例):
\nimport camelot\nfile = \'relacao_medicamentos_rename_2020.pdf\'\ntables = camelot.read_pdf(file, pages=\'17, 18\', flavor=\'stream\', row_tol=20, strip_text=\'\\n\') \ntables.export(\'foo.csv\', f=\'csv\', compress=False)\nRun Code Online (Sandbox Code Playgroud)\n尽管如此,这样您最终会得到每页一个表格和每个表格一个 csv 文件。即在上面的示例中,您将获得两个 .csv 文件。这需要在 Camelot 外部处理。\n要使用 pandas 合并跨多个页面的表:
\nimport pandas as pd\ndfs = [] # list to store dataframes\nfor table in tables:\n df = table.df\n df.columns = df.iloc[0] # use first row as header\n df = df[1:] # remove the first row from the dataframe\n dfs.append(df)\ndf = pd.concat(dfs, axis=0) # concatenate all dataframes in list \ndf.to_csv(\'foo.csv\') # export dataframe to csv\nRun Code Online (Sandbox Code Playgroud)\n此外,在包含文本和表格的页面(例如 pdf 第 16 页)上识别表格区域也很困难。\n在这些情况下,可以指定表格区域。对于第 16 页的表格,这将是:
\ntables = camelot.read_pdf(in_dir + file, pages=\'16\', flavor=\'stream\', row_tol=20, strip_text=\'\\n\', table_areas=[\'35,420,380,65\'],)\nRun Code Online (Sandbox Code Playgroud)\n注意:在整篇文章中,我通过“计算”文件的页数来引用页面,而不是通过每页上打印的页码(后者从文档的第二页开始)。
\n| 归档时间: |
|
| 查看次数: |
5210 次 |
| 最近记录: |