【问题标题】:Maintaining Data Type in Colaboratory在 Colaboratory 中维护数据类型
【发布时间】:2018-06-20 21:56:42
【问题描述】:

我正在尝试使用 PyPDF2 读取 pdf 文档并输出纯文本字符串。但是,当我使用代码将我的 pdf 文件上传到 colaboratory 时:

uploaded = files.upload()

for fn in uploaded.keys():
  print('User uploaded file "{name}" with length {length} bytes'.format(
  name=fn, length=len(uploaded[fn])))

它会自动将其转换为 str 类型,而不是将其保留为编码字符串。这会导致 PyPDF.PdfFileReader() 出错,但如果您打印字符串,它仍然包含所有编码字符:

gsutilCheatSheet.pdf => %PDF-1.5 %���� 1 0 对象 >/元数据 117 0 R/ViewerPreferences 118 0 R>> 结束对象

等等

有没有办法让导入的文档保持原始编码格式,或者一旦它已经是一个str,有没有其他方法可以删除编码?

【问题讨论】:

    标签: python pdf google-colaboratory


    【解决方案1】:

    我怀疑您需要将上传的文件包装在 io.BytesIO 中。

    这是一个完整的示例,展示了如何使用 PyPDF2 打开上传的 PDF -- https://colab.research.google.com/notebook#fileId=1XlmXcp4xnrUGMUArevxiGNlrbMOMECO1

    关键位是:

    pdf = PdfFileReader(io.BytesIO(uploaded['abc123.pdf']))

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-08
      • 1970-01-01
      • 2015-10-17
      • 2018-11-12
      • 1970-01-01
      • 1970-01-01
      • 2013-10-31
      • 2011-11-13
      相关资源
      最近更新 更多