用pdfminer转换几个文件

时间:2016-11-28 17:21:34

标签: python glob pdfminer

我发现在线代码允许使用Python中的pdfminer模块将多个pdf文件转换为文本文件。我试图扩展我保存在目录中的几个pdf文件的代码,但代码导致错误。

到目前为止我的代码:

import nltk
import re
import glob

from cStringIO import StringIO
from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.converter import TextConverter
from pdfminer.layout import LAParams
from pdfminer.pdfpage import PDFPage

def convert(fname, pages=None):
   if not pages:
       pagenums = set()
    else:
       pagenums = set(pages)

   output = StringIO()
   manager = PDFResourceManager()
   converter = TextConverter(manager, output, laparams=LAParams())
   interpreter = PDFPageInterpreter(manager, converter)

   infile = file(fname, 'rb')
   for page in PDFPage.get_pages(infile, pagenums):
       interpreter.process_page(page)
   infile.close()
   converter.close()
   text = output.getvalue()
   output.close

   with open('D:\Reports\*.txt', 'w') as pdf_file:
       pdf_file.write(text)

   return text

directory = glob.glob('D:\Reports\*.pdf')  

for myfiles in directory:  
     convert(myfiles)

错误消息:

Traceback (most recent call last):
  File "F:/Text mining/pdfminer for several files", line 40, in <module>
    convert(myfiles)
  File "F:/Text mining/pdfminer for several files", line 32, in convert
    with open('D:\Reports\*.txt', 'w') as pdf_file:
IOError: [Errno 22] invalid mode ('w') or filename: 'D:\\Reports\\*.txt'

2 个答案:

答案 0 :(得分:1)

错误源于尝试将text变量的内容写入名为'D:\Reports\*.txt'的文件。文件名(ref)中不允许使用通配符*

如果要将文件保存为具有相同名称的文本文件,可以将编写功能替换为:

   outfile = os.path.splitext(os.path.abspath(fname))[0] + '.txt'
   with open(outfile, 'wb') as pdf_file:
       pdf_file.write(text)

如果您想以操作系统无关的方式处理路径,请不要忘记import os

答案 1 :(得分:0)

可能你应该改变:

with open('D:\Reports\*.txt', 'w') as pdf_file:
    pdf_file.write(text)

with open(fname, 'w') as pdf_file:
    pdf_file.write(text)

但我的机器上没有python2.7-3.4可供验证