Table of Contents
Example 2
Summary
Home Backend Development Python Tutorial How to crawl tabular data from PDF files in Python (code example)

How to crawl tabular data from PDF files in Python (code example)

Oct 24, 2018 pm 05:15 PM
python

The content of this article is about how Python can crawl tabular data from PDF files (code examples). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you. .

This article will show a slightly different crawler.
 In the past, our crawlers crawled data from the Internet, because web pages are generally written in HTML, CSS, and JavaScript codes. Therefore, there are a large number of mature technologies to crawl various data in web pages. This time, the documents we need to crawl are PDF files. This article will show how to use Python's camelot module to crawl tabular data from PDF files.
In our daily life and work, PDF files are undoubtedly one of the most commonly used file formats. We can all see this file format, ranging from textbooks and courseware to contracts and planning documents. But how to extract tables from PDF files is a big problem. Because there is no internal representation in PDF to represent a table. This makes tabular data difficult to extract for analysis. So, how do we crawl table data from PDF?
The answer is Python’s camelot module!
 camelot is a module for Python that allows anyone to easily extract tabular data from PDF files. You can use the following command to install the camelot module (it takes a long time to install):

pip install camelot-py
Copy after login

The official documentation address of the camelot module is: https://camelot-py.readthedoc....
The following will show how to use the camelot module to crawl tabular data from PDF files.

Example 1

 First, let us look at a simple example: eg.pdf. The entire file has only one page, and there is only one table in this page, as follows:

How to crawl tabular data from PDF files in Python (code example)

Use the following Python code to extract the table in the PDF file:

import camelot

# 从PDF文件中提取表格
tables = camelot.read_pdf('E://eg.pdf', pages='1', flavor='stream')

# 表格信息
print(tables)
print(tables[0])
# 表格数据
print(tables[0].data)
Copy after login

The output result is:

<tablelist>
<table>
[['ID', '姓名', '城市', '性别'], ['1', 'Alex', 'Shanghai', 'M'], ['2', 'Bob', 'Beijing', 'F'], ['3', 'Cook', 'New York', 'M']]<p>Analysis code, camelot.read_pdf() is camelot's function to extract data from a table. The input parameters are the path of the PDF file, the page number (pages) and the table parsing method (there are two methods, stream and lattice). For the table parsing method, the default method is lattice, and the stream method will parse the entire PDF page as a table by default. If you need to specify the area in the parsed page, you can use the table_area parameter. <br> The convenience of the camelot module is that it provides functions to directly convert extracted table data into pandas, csv, JSON, and html, such as tables[0].df, tables[0].to_csv() function wait. Let’s take the output csv file as an example: </p>
<pre class="brush:php;toolbar:false">import camelot

# 从PDF文件中提取表格
tables = camelot.read_pdf('E://eg.pdf', pages='1', flavor='stream')

# 将表格数据转化为csv文件
tables[0].to_csv('E://eg.csv')
Copy after login

The obtained csv file is as follows:

How to crawl tabular data from PDF files in Python (code example)

Example 2

In Example 2, we will extract table data in a certain area of ​​the PDF page. The pages (parts) of the PDF file are as follows:

How to crawl tabular data from PDF files in Python (code example)

In order to extract the only table in the entire page, we need to locate the location of the table. The coordinate system of the PDF file is different from that of the picture. It takes the vertex of the lower left corner as the origin, the x-axis to the right, and the y-axis upward. The coordinates of the text on the entire page can be output through the following Python code:

import camelot

# 从PDF中提取表格
tables = camelot.read_pdf('G://Statistics-Fundamentals-Succinctly.pdf', pages='53', \
                          flavor='stream')

# 绘制PDF文档的坐标,定位表格所在的位置
tables[0].plot('text')
Copy after login

The output result is:

UserWarning: No tables found on page-53 [stream.py:292]
Copy after login

The entire code does not find the table. This is because the stream method treats the entire PDF page as a table by default, so the table is not found. But the image of the drawn page coordinates is as follows:

How to crawl tabular data from PDF files in Python (code example)

Carefully comparing the previous PDF pages, we can easily find that the coordinates of the upper left corner of the area corresponding to the table is (50,620), and the coordinates of the lower right corner are (500,540). We add the table_area parameter to the read_pdf() function. The complete Python code is as follows:

import camelot

# 识别指定区域中的表格数据
tables = camelot.read_pdf('G://Statistics-Fundamentals-Succinctly.pdf', pages='53', \
                          flavor='stream', table_area=['50,620,500,540'])

# 绘制PDF文档的坐标,定位表格所在的位置
table_df = tables[0].df

print(type(table_df))
print(table_df.head(n=6))
Copy after login

The output result is:

<class>
         0               1                2           3
0  Student  Pre-test score  Post-test score  Difference
1        1              70               73           3
2        2              64               65           1
3        3              69               63          -6
4        …               …                …           …
5       34              82               88           6</class>
Copy after login

Summary

In specific identification of PDF pages When creating a table, in addition to the parameter of specifying the area, there are also parameters such as superscript and subscript, cell merging, etc. For detailed usage, please refer to the camelot official document website: https://camelot-py.readthedoc....

The above is the detailed content of How to crawl tabular data from PDF files in Python (code example). For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Can vs code run in Windows 8 Can vs code run in Windows 8 Apr 15, 2025 pm 07:24 PM

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

Can visual studio code be used in python Can visual studio code be used in python Apr 15, 2025 pm 08:18 PM

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

How to run python with notepad How to run python with notepad Apr 16, 2025 pm 07:33 PM

Running Python code in Notepad requires the Python executable and NppExec plug-in to be installed. After installing Python and adding PATH to it, configure the command "python" and the parameter "{CURRENT_DIRECTORY}{FILE_NAME}" in the NppExec plug-in to run Python code in Notepad through the shortcut key "F6".

How to run sublime code python How to run sublime code python Apr 16, 2025 am 08:48 AM

To run Python code in Sublime Text, you need to install the Python plug-in first, then create a .py file and write the code, and finally press Ctrl B to run the code, and the output will be displayed in the console.

See all articles