繁体   English   中英

协助完善将Python脚本的输出保存到文本文件

[英]Assistance with refining saving output from Python script to text file

我需要一点帮助来弄清楚为什么它不能按预期工作。 以下代码打开一个PDF文件,提取文本,并应根据PDF文件的名称保存单个文本文件,但是不会产生任何输出。 请帮忙。 代码如下:

import PyPDF2
import os
import glob


directory = 'C:/LIVE/2017/'

fileStructure = glob.glob("C:/LIVE/2017/*")
names = [os.path.basename(x) for x in glob.glob('C:/LIVE/2017/*')]

for file in os.listdir(directory):
    with open(os.path.join(directory,file), 'rb') as pdfFileObj:
        pdfReader = PyPDF2.PdfFileReader(pdfFileObj, strict=False)
        pageObj = pdfReader.getPage(0)
        number_of_pages = pdfReader.getNumPages()

        for page_number in range(number_of_pages):
            page = pdfReader.getPage(page_number)
            page_content = page.extractText().encode('utf-8')
            getFileName = os.path.basename(pdfFileObj.name)
            bcn = getFileName.rsplit(' ', 1)[-1]
            bcNum = os.path.splitext(os.path.basename(bcn))[0]
            text_file = open(bcNum, "w")
            text_file.write(page_content)
            text_file.close()

它是否从PDF提取字符串开始? 我以前尝试过使用PyPDF2,但发现如果格式不正确,通常很难从PDF获取文本。 使用模块Tika取得了更多的成功。

from tika import parser

def read_pdf(pdf):
    raw = parser.from_file(pdf)
    return raw['content']

text_list = list()
for file in os.listdir(directory):
    raw_content = read_pdf(pdf)
    text_list.append(raw_content)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM