TypeError:期望一个字符缓冲区对象

时间:2014-06-07 18:59:20

标签: python pyscripter

我一直在尝试将输出打印到新的文本文件中。但我收到了错误

TypeError: expected a character buffer object

我要做的是将pdf转换为文本并将获得的文本复制到新文件中。

import pyPdf

def getPDFContent():
  content = ""
  # Load PDF into pyPDF
  pdf = pyPdf.PdfFileReader(file("D:\output.pdf", "rb"))
  # Iterate pages
  for i in range(0, pdf.getNumPages()):
    # Extract text from page and add to content
    #content += pdf.getPage(i).extractText() + "\n"
    print pdf.getPage(i).extractText().encode("ascii", "ignore")

  # Collapse whitespace
  #content = " ".join(content.replace(u"\xa0", " ").strip().split())
  #return content

  #getPDFContent().encode("ascii", "ignore")
  getPDFContent()

  s =getPDFContent()
  with open('D:\pdftxt.txt', 'w') as pdftxt:
      pdftxt.write(s)

我确实尝试将s初始化为str,但之后我收到了错误,因为"无法分配给函数调用"。

1 个答案:

答案 0 :(得分:1)

您没有返回任何getPDFContent(),所以基本上您正在撰写None

 result=[]
 for i in range(0, pdf.getNumPages()):
     result.append(pdf.getPage(i).extractText().encode("ascii", "ignore")) # store all in a list
 return result


 s = getPDFContent()
 with open('D:\pdftxt.txt', 'w') as pdftxt:
    pdftxt.writelines(s) # use writelines to write list content

您的代码应如何显示:

def getPDFContent():
    # Load PDF into pyPDF
    pdf = pyPdf.PdfFileReader(file("D:\output.pdf", "rb"))
    # Iterate pages
    result = []
    for i in range(0, pdf.getNumPages()):
        result.append(pdf.getPage(i).extractText().encode("ascii", "ignore"))
    return result

s = getPDFContent()
with open('D:\pdftxt.txt', 'w') as pdftxt:
    pdftxt.writelines(s)