【问题标题】:How to read the pdf file in a line by line string in Python/Django?如何在 Python/Django 中逐行读取 pdf 文件?
【发布时间】:2013-04-02 03:37:40
【问题描述】:

我正在处理等于或小于5KB 的文本和pdf 文件。如果文件是文本文件,我会从表单中获取文件并在字符串中获取所需的输入以进行汇总:

 file = file.readlines()
 file = ''.join(file)
 result = summarize(file, num_sentences)

这很容易完成,但对于 pdf 文件,事实证明这并不容易。有没有办法像我在 Python/Django 中处理我的 txt 文件一样将 pdf 文件的句子作为字符串获取?

【问题讨论】:

  • 这可能是这个问题的重复:stackoverflow.com/questions/2481945/…
  • 是的,可能。但是我已经尝试了该问题中的建议解决方案。它无法以字符串形式返回所有文件的内容。
  • 也许你可以在你的问题中这样说,并说出到底出了什么问题(错误信息?错误的内容?),以便我们为您提供帮助!
  • 您可以使用这个应用程序:unixuser.org/~euske/python/pdfminer/index.html

标签: python django pdf file-io readlines


【解决方案1】:

我认为不可能像使用 txt 文件那样阅读 pdf,您需要将 pdf 转换为 txt 文件(参考 Python module for converting PDF to text)然后处理它。 你也可以参考这个轻松将pdf转txthttp://code.activestate.com/recipes/511465-pure-python-pdf-to-text-converter/

【讨论】:

    【解决方案2】:

    在 Django 中你可以这样做:

    views.py:

    def upload_pdf():
         if request.method == 'POST' and request.FILES['myfile']:
            pdfFileObj = request.FILES['myfile'].read() 
            pdfReader = PyPDF2.PdfFileReader(io.BytesIO(pdfFileObj))
            NumPages = pdfReader.numPages
            i = 0
            content = []
            while (i<NumPages):
                text = pdfReader.getPage(i)
                content.append(text.extractText())
                i +=1
           # depends on what you want to do with the pdf parsing results
           return render(request, .....) 
    

    html部分:

    <form method="post" enctype="multipart/form-data" action="/url">
        {% csrf_token %}
          <input  type="file" name="myfile"> # the name is the same as the one you put in FILES['myfile']
        <button class="butto" type="submit">Upload</button>
    </form>
    

    在 Python 中,您可以简单地这样做:

    fileName = "path/test.pdf"
    pdfFileObj = open(fileName,'rb')
    pdfReader = PyPDF2.PdfFileReader(pdfFileObj)
    NumPages = pdfReader.numPages
    
    i = 0
    content = []
    while (i<NumPages):
        text = pdfReader.getPage(i)
        content.append(text.extractText())
        i +=1
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-21
      • 2019-04-16
      • 2014-11-11
      • 1970-01-01
      • 2012-07-18
      • 1970-01-01
      相关资源
      最近更新 更多