Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/319.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在不下载Python的情况下从url提取文本pdf_Python_Pdf_Python Requests - Fatal编程技术网

如何在不下载Python的情况下从url提取文本pdf

如何在不下载Python的情况下从url提取文本pdf,python,pdf,python-requests,Python,Pdf,Python Requests,我目前正在使用requests.get从API提取pdf。我不想下载它们,只是想从中提取文本 response\u pdf=requests.get(url,auth=TokenAuth(key)) text=将pdf格式转换为txt格式(response\u pdf.content) 下面是函数convert_pdf_to_txt的代码: def将pdf文件转换为txt文件(文件名): rsrcmgr=PDFResourceManager() retstr=StringIO() 编解码器='

我目前正在使用requests.get从API提取pdf。我不想下载它们,只是想从中提取文本

response\u pdf=requests.get(url,auth=TokenAuth(key))
text=将pdf格式转换为txt格式(response\u pdf.content)
下面是函数convert_pdf_to_txt的代码:

def将pdf文件转换为txt文件(文件名):
rsrcmgr=PDFResourceManager()
retstr=StringIO()
编解码器='utf-8'
#编解码器='ISO-8859-1'
laparams=laparams()
device=TextConverter(rsrcmgr、retstr、codec=codec、laparams=laparams)
fp=打开(文件名为“rb”)
解释器=PDFPAGE解释器(rsrcmgr,设备)
password=“”
maxpages=0
缓存=真
pagenos=set()
对于PDFPage.get_页面中的页面(fp,pagenos,maxpages=maxpages,password=password,caching=caching,check_extractable=True):
解释器。处理页面(第页)
text=retstr.getvalue()
fp.close()
设备关闭()
retstr.close()
text=str(text)
text=文本。替换(“\\n”和“”)
text=text.lower()
返回文本
我得到以下错误: UnicodeDecodeError:“utf-8”编解码器无法解码位置11中的字节0xb5:无效的开始字节

响应是一个“class'bytes'”对象,我不知道如何从中提取文本


任何帮助都将不胜感激

您正在传入一个bytestring以解释为要打开的文件名,这不好

相反,您可以将bytestring读入
io.BytesIO()
并将其作为
fp
传递:

def convert_pdf_to_txt(fp):
    rsrcmgr = PDFResourceManager()
    retstr = StringIO()
    codec = "utf-8"
    # codec ='ISO-8859-1'
    laparams = LAParams()
    device = TextConverter(
        rsrcmgr, retstr, codec=codec, laparams=laparams
    )

    interpreter = PDFPageInterpreter(rsrcmgr, device)
    password = ""
    maxpages = 0
    caching = True
    pagenos = set()

    for page in PDFPage.get_pages(
        fp,
        pagenos,
        maxpages=maxpages,
        password=password,
        caching=caching,
        check_extractable=True,
    ):
        interpreter.process_page(page)

    text = retstr.getvalue()
    device.close()
    retstr.close()
    text = str(text)
    text = text.replace("\\n", "")
    text = text.lower()
    return text

response_pdf = requests.get(url, auth=TokenAuth(key))
pdf_stream = io.BytesIO(response_pdf.content)
text = convert_pdf_to_txt(pdf_stream)
它还有一个额外的优点,即您仍然可以在文件中使用它:

打开('my_pdf','rb')作为pdf_流:
text=将pdf格式转换为txt格式(pdf格式)

请为您收到的错误添加完整的回溯。