如何在 Python 3.7 中从 pdf 中提取文本 [英] How to extract text from pdf in Python 3.7
问题描述
我正在尝试使用 Python 从 PDF 文件中提取文本.我的主要目标是我正在尝试创建一个程序来读取银行对账单并提取其文本以更新 excel 文件以轻松记录每月支出.现在我只专注于从 pdf 文件中提取文本,但我不知道该怎么做.
I am trying to extract text from a PDF file using Python. My main goal is I am trying to create a program that reads a bank statement and extracts its text to update an excel file to easily record monthly spendings. Right now I am focusing just extracting the text from the pdf file but I don't know how to do so.
目前将 PDF 文件中的文本提取为字符串的最佳和最简单的方法是什么?今天最好使用哪个库,我该怎么做?
What is currently the best and easiest way to extract text from a PDF file into a string? What library is best to use today and how can I do it?
我曾尝试使用 PyPDF2,但每次我尝试使用 extractText() 从任何页面提取文本时,它都会返回空字符串.我曾尝试安装 textract,但出现错误,因为我认为我需要更多库.
I have tried using PyPDF2 but everytime I try to extract text from any page using extractText(), it returns empty strings. I have tried installing textract but I get errors because I need more libraries I think.
import PyPDF2
pdfFileObj = open("January2019.pdf", 'rb')
pdfReader = PyPDF2.PdfFileReader(pdfFileObj)
pageObj = pdfReader.getPage(0)
print(pageObj.extractText())
这在应该打印页面内容时打印空字符串
This prints empty strings when it should be printing the contents of the page
推荐答案
使用 tika 对我有用!
Using tika worked for me!
from tika import parser
rawText = parser.from_file('January2019.pdf')
rawList = rawText['content'].splitlines()
这使得将银行对账单中的每一行单独提取到一个列表中变得非常容易.
This made it really easy to extract separate each line in the bank statement into a list.
这篇关于如何在 Python 3.7 中从 pdf 中提取文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!