簡體   English   中英

如何在Python / Django中逐行讀取pdf文件?

[英]How to read the pdf file in a line by line string in Python/Django?

我正在處理等於或小於5KB的文本和pdf文件。 如果文件是文本文件,我將從表單中獲取文件,並以字符串形式獲取所需的輸入以進行匯總:

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

這很容易做到,但是對於pdf文件,事實並非如此簡單。 有沒有辦法像在Python / Django中使用txt文件那樣將pdf文件的句子作為字符串獲取?

我不認為有可能像處理txt文件一樣讀取pdf,需要將pdf轉換為txt文件(請參閱Python模塊將PDF轉換為文本 ),然后進行處理。 您也可以參考此文件,輕松地將pdf轉換為txt http://code.activestate.com/recipes/511465-pure-python-pdf-to-text-converter/

在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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM