最近運行課件代碼呢蔫,發(fā)現(xiàn)pdf文件讀取部分的函數(shù)失效切心。這里找到讀取pdf文件的可運行代碼,為了方便后續(xù)學(xué)習(xí)使用片吊,我已將pdf和docx讀取方法封裝成pdfdocx包绽昏。
pdfdocx
只有簡單的兩個讀取函數(shù)
- read_pdf(file)
- read_docx(file)
file為文件路徑,函數(shù)運行后返回file文件內(nèi)的文本數(shù)據(jù)俏脊。
安裝
pip install pdfdocx
使用
讀取pdf文件
from pdfdocx import read_pdf
p_text = read_pdf('test/data.pdf')
print(p_text)
Run
這是來?pdf?件內(nèi)的內(nèi)容
from pdfdocx import read_docx
d_text = read_pdf('test/data.docx')
print(d_text)
Run
這是來?docx?件內(nèi)的內(nèi)容
拆開pdfdocx
希望大家能安裝好全谤,如果安裝或者使用失敗,可以使用下面的代碼作為備選方法爷贫。雖然繁瑣认然,能用就好。
讀取pdf
from io import StringIO
from pdfminer.converter import TextConverter
from pdfminer.layout import LAParams
from pdfminer.pdfdocument import PDFDocument
from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.pdfpage import PDFPage
from pdfminer.pdfparser import PDFParser
import re
def read_pdf(file):
"""
讀取pdf文件漫萄,并返回其中的文本內(nèi)容
:param file: pdf文件路徑
:return: docx中的文本內(nèi)容
"""
output_string = StringIO()
with open(file, 'rb') as in_file:
parser = PDFParser(in_file)
doc = PDFDocument(parser)
rsrcmgr = PDFResourceManager()
device = TextConverter(rsrcmgr, output_string, laparams=LAParams())
interpreter = PDFPageInterpreter(rsrcmgr, device)
for page in PDFPage.create_pages(doc):
interpreter.process_page(page)
text = output_string.getvalue()
return re.sub('[\n\t\s]', '', text)
讀取docx
import docx
def read_docx(file):
"""
讀取docx文件季眷,并返回其中的文本內(nèi)容
:param file: docx文件路徑
:return: docx中的文本內(nèi)容
"""
text = ''
doc = docx.Document(file)
for para in doc.paragraphs:
text += para.text
return text
如果
如果您是經(jīng)管人文社科專業(yè)背景,編程小白卷胯,面臨海量文本數(shù)據(jù)采集和處理分析艱巨任務(wù)子刮,個人建議學(xué)習(xí)《python網(wǎng)絡(luò)爬蟲與文本數(shù)據(jù)分析》視頻課。作為文科生,一樣也是從兩眼一抹黑開始挺峡,這門課程是用五年時間凝縮出來的葵孤。自認為講的很通俗易懂o( ̄︶ ̄)o,
- python入門
- 網(wǎng)絡(luò)爬蟲
- 數(shù)據(jù)讀取
- 文本分析入門
- 機器學(xué)習(xí)與文本分析
- 文本分析在經(jīng)管研究中的應(yīng)用
感興趣的童鞋不妨 戳一下《python網(wǎng)絡(luò)爬蟲與文本數(shù)據(jù)分析》進來看看~
更多
公眾號:大鄧和他的python
-
?