2017-11-12 15 views
-1

ウェブサイトからpdfファイルをダウンロードしてテキストで作業したい。しかし、私はpdfファイルを作成してテキストに変換したくありません。私はPythonのリクエストを使用します。次のコードの直後にテキストを取得する方法はありますか?ファイルを作成せずにpdfをテキストに変換する

res = requests.get(url, timeout=None)

+1

「[Pythonを使用してPDFファイルからテキストを抽出する]」の複製が可能です(https://stackoverflow.com/questions/34837707/extracting-text-from-a-pdf-file-using-python) – phd

+1

OPは「これはできますか?」と尋ねているので、^の複製ではありません。答えは「いいえ」です。 –

+0

あなたの質問に答えられたら、[回答を受け入れる](https://stackoverflow.com/help/someone-answers)をお願いします。 –

答えて

0

いいえ、requests(でも私の知る限りでは、他のモジュール)だけで、この機能をサポートしていません。まずrequestsでPDFファイルをダウンロードし、マイニングツールを使用してテキストを抽出します。私はpdftotextコマンドラインツールを使用するのが好きです。ここで

あなたは、通常のpythonからそれをインターフェイスしたい方法は次のとおりです。

process = subprocess.Popen('pdftotext {}'.format(filepath), 
            shell=True, stdout=subprocess.PIPE) 
text, _ = process.communicate() 

textは、あなたのテキストが含まれています。

0

AFAIKの場合、 プロセスを実行できるように、少なくとも一時ファイルを作成する必要があります。

次のコードを使用して、PDFファイルを取得/読み取りし、それをTEXTファイルに変換することができます。 これはPDFMINERとPython 3.7を使用します。上記のプログラムを呼び出すための

from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter 
from pdfminer.converter import HTMLConverter,TextConverter,XMLConverter 
from pdfminer.layout import LAParams 
from pdfminer.pdfpage import PDFPage 
import io 

def convert(case,fname, pages=None): 
    if not pages: 
     pagenums = set() 
    else: 
     pagenums = set(pages) 
    manager = PDFResourceManager() 
    codec = 'utf-8' 
    caching = True 
    output = io.StringIO() 
    converter = TextConverter(manager, output, codec=codec, laparams=LAParams()) 
    interpreter = PDFPageInterpreter(manager, converter) 
    infile = open(fname, 'rb') 
    for page in PDFPage.get_pages(infile, pagenums, caching=caching, check_extractable=True): 
     interpreter.process_page(page) 

    convertedPDF = output.getvalue() 
    print(convertedPDF) 

    infile.close() 
    converter.close() 
    output.close() 
    return convertedPDF 

主な機能:もちろん

import os 
import converter 
import sys, getopt 

class ConvertMultiple: 
    def convert_multiple(pdf_dir, txt_dir): 
     if pdf_dir == "": pdf_dir = os.getcwd() + "\\" # if no pdfDir passed in 
     for pdf in os.listdir(pdf_dir): # iterate through pdfs in pdf directory 
      print("File name is %s", os.path.basename(pdf)) 
      file_extension = pdf.split(".")[-1] 
      print("file extension is %s", file_extension) 
      if file_extension == "pdf": 
       pdf_file_name = pdf_dir + pdf 
       path = 'E:/pdf/' + os.path.basename(pdf) 
       print(path) 
       text = converter.convert('text', path) # get string of text content of pdf 
       text_file_name = txt_dir + pdf + ".txt" 
       text_file = open(text_file_name, "w") # make text file 
       text_file.write(text) # write text to text file 


pdf_dir = "E:/pdf" 
txt_dir = "E:/text" 
ConvertMultiple.convert_multiple(pdf_dir, txt_dir) 

あなたは調整でき、それいくつかのより多くの改善のためのいくつかのより多くの部屋であってもよいが、この事は確かに働くことがあります。

pdfフォルダを提供する代わりに、一時PDFファイル を直接提供してください。

これはあなたに役立つことを期待しています..ハッピーコーディング!