【问题标题】:Issue scraping a PDF with Python then encoding in utf-8使用 Python 抓取 PDF 然后以 utf-8 编码的问题
【发布时间】:2016-07-18 00:28:51
【问题描述】:

我正在使用 Python 从网上抓取一些 pdf,以便我可以将它们转换为文本文件以便在 R 中进行分析。

我正在使用 pdfminer,然后将它们编码为 utf-8,但完成的文本文件仍然包含许多字节对象的表示形式(例如 '\xe2\x80\x94'),而不是所需的字符本身。

我的查询类似于Why won't Python display this text correctly? (UTF-8 Decoding Issue),不同之处在于我已经在 utf-8 中编码了我的字节对象并且仍然遇到同样的问题。

我的代码如下:

from pdfminer.converter import TextConverter
from io import StringIO
from io import open
from urllib.request import urlopen

def readPDF(pdfile):
    rsrcmgr=PDFResourceManager()
    retstr=StringIO()
    laparams=LAParams()
    device=TextConverter(rsrcmgr,retstr,laparams=laparams)
    process_pdf(rsrcmgr,device,pdfFile)
    device.close()
    content=retstr.getvalue()
    retstr.close()
    return content`

pdfFile=urlopen(webaddress)
outputString=readPDF(pdfFile)
proceedings=outputString.encode('utf-8')
proceedings=str(proceedings)
file=open(filename,"w")
file.write(proceedings)
file.close()

抱歉,如果这很简单。我对 Python 很陌生。

【问题讨论】:

    标签: python-3.x pdf unicode utf-8 ascii


    【解决方案1】:

    以下代码块是不必要的,并且可能会错误地对您的数据进行编码和解码。请参阅内联 cmets。

    proceedings=outputString.encode('utf-8') # creates a UTF-8 byte object
    proceedings=str(proceedings) # creates string representation <- the source of your issue
    file=open(filename,"w") # encodes str to platform specific encoding.
    

    编辑:感谢@MarkTolonen:str() 返回字节的“非正式”或可很好打印的str(默认情况下不会像我想的那样解码)。 IE。 proceedings == "b'stuff'"

    第一步是简单地阻止并消除歧义。当你open()输出文件时设置编码:

    file=open(filename,"w", encoding="utf-8")
    file.write(proceedings)
    file.close()
    

    提示。使用with 语句设置文件上下文。这允许文件在上下文完成后关闭。此外,最好不要使用file,因为它也是一种类型。将上面的代码替换为:

    with open(filename, 'w', encoding="utf-8") as proceedings_file:
        proceedings_file.write(proceedings)
    

    【讨论】:

    • file 不再是 Python 3 中的类型。
    • str(proceedings) 实际上返回上一行创建的字节对象的字符串表示,例如,"b'stuff'"
    • 嗨@MarkTolonen。是的,这就是我写的 - str(proceedings) 创建一个 [Unicode] str [从字节(通过解码)]。正确的?感谢file 的提示。
    • 啊,我明白你的意思了。我认为str() 使用隐含的默认编码解码。所以我的回答应该解决 OP 的回答——尽管是间接的:$
    • 谢谢。我试试看!
    猜你喜欢
    • 1970-01-01
    • 2018-02-18
    • 1970-01-01
    • 2010-12-01
    • 1970-01-01
    • 2017-04-24
    相关资源
    最近更新 更多