2010-01-07 1 views
1

여기 내 코드, 나는 그것이 끔찍 확신하지만 모든 작품입니다 ... 감안할 때내가 이해하지 못하는 유니 코드 오류가 나는 데에만 문제가 마지막 줄에 함께 예상대로

import pyPdf 
import os 
import csv 

class UnicodeWriter: 
    """ 
    A CSV writer which will write rows to CSV file "f", 
    which is encoded in the given encoding. 
    """ 

    def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds): 
     # Redirect output to a queue 
     self.queue = cStringIO.StringIO() 
     self.writer = csv.writer(self.queue, dialect=dialect, **kwds) 
     self.stream = f 
     self.encoder = codecs.getincrementalencoder(encoding)() 

    def writerow(self, row): 
     self.writer.writerow([s.encode("utf-8") for s in row]) 
     # Fetch UTF-8 output from the queue ... 
     data = self.queue.getvalue() 
     data = data.decode("utf-8") 
     # ... and reencode it into the target encoding 
     data = self.encoder.encode(data) 
     # write to the target stream 
     self.stream.write(data) 
     # empty queue 
     self.queue.truncate(0) 

    def writerows(self, rows): 
     for row in rows: 
      self.writerow(row) 


    PDFWriter = csv.writer(open('/home/nick/TAM_work/text/text.doc', 'a'), delimiter=' ', quotechar='|', quoting=csv.QUOTE_ALL) 

    def getPDFContent(path): 
     content = "" 
     # Load PDF into pyPDF 
     pdf = pyPdf.PdfFileReader(file(path, "rb")) 
     # Iterate pages 
     for i in range(0, pdf.getNumPages()): 
      # Extract text from page and add to content 
      content += pdf.getPage(i).extractText() + "\n" 
     # Collapse whitespace 
     content = " ".join(content.replace(u"\xa0", " ").strip().split()) 
     return content 

    for word in os.listdir("/home/nick/TAM_work/TAM_pdfs"): 
    print getPDFContent("/home/nick/TAM_work/TAM_pdfs/" + word) 

    PDFWriter.writerow ([getPDFContent("/home/nick/TAM_work/TAM_pdfs/" + word)]) 
그것은이 돌 때까지

나는 그것을 실행하는 모든

Traceback (most recent call last): 
    File "Saving_fuction_added.py", line 52, in <module> 
    PDFWriter.writerow ([getPDFContent("/home/nick/TAM_work/TAM_pdfs/" + word)]) 
UnicodeEncodeError: 'ascii' codec can't encode character u'\u2122' in position 81: ordinal not in range(128) 

내가 어떤 도움을 싶지만 ... 작동합니다. 고마워.

매트

+0

비 ASCII 파일 이름이 있습니까? stacktrace가 너무 짧기 때문에 혼란 스럽습니다. writerow() 함수가 아닌 목록 이해 (TAM_pdfs + word) 내에 오류가 있음을 나타내는 것 같습니다. –

+0

나는 처음에는 그렇게 생각했지만 이전 줄에서는 실패하지 않겠는가? – danben

+0

를 .csv 내 .DOC를 변경하고 시도 추가 시도 : # 값이 있었다 : 다른 ("UTF-8", 값) 값 = 유니 코드 : UnicodeError 제외 X = 유니 코드 (값, "아스키") 을 유효한 ASCII 데이터 패스 하지만 그건 작동하지 않았다. 어쩌면 나는 완전히 잘못된 길을보고있을 것입니까? 텍스트를 CSV 파일로 추출하면됩니다. – Matt

답변

1

다음은이 질문에 대한 답변입니다. 그러나 이제는 마지막 파일 만 씁니다.

import pyPdf 
import os 
import csv 

class UnicodeWriter: 
    """ 
    A CSV writer which will write rows to CSV file "f", 
    which is encoded in the given encoding. 
    """ 

    def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds): 
     # Redirect output to a queue 
     self.queue = cStringIO.StringIO() 
     self.writer = csv.writer(self.queue, dialect=dialect, **kwds) 
     self.stream = f 
     self.encoder = codecs.getincrementalencoder(encoding)() 

    def writerow(self, row): 
     self.writer.writerow([s.encode("utf-8") for s in row]) 
     # Fetch UTF-8 output from the queue ... 
     data = self.queue.getvalue() 
     data = data.decode("utf-8") 
     # ... and reencode it into the target encoding 
     data = self.encoder.encode(data) 
     # write to the target stream 
     self.stream.write(data) 
     # empty queue 
     self.queue.truncate(0) 

    def writerows(self, rows): 
     for row in rows: 
      self.writerow(row) 


PDFWriter = csv.writer(open('/home/nick/TAM_work/text/text.doc', 'a'), delimiter=' ', quotechar='|', quoting=csv.QUOTE_ALL) 

def getPDFContent(path): 
    content = "" 
    # Load PDF into pyPDF 
    pdf = pyPdf.PdfFileReader(file(path, "rb")) 
    # Iterate pages 
    for i in range(0, pdf.getNumPages()): 
     # Extract text from page and add to content 
     content += pdf.getPage(i).extractText() + "\n" 
    # Collapse whitespace 
    content = " ".join(content.replace(u"\xa0", " ").strip().split()) 
    return content 

for word in os.listdir("/home/nick/TAM_work/TAM_pdfs"): 
    print getPDFContent("/home/nick/TAM_work/TAM_pdfs/" + word) 

PDFWriter.writerow ([getPDFContent("/home/nick/TAM_work/TAM_pdfs/" + word).encode("ascii", "ignore")]) 
+0

을 다시 수정하여 for 루프에 PDFWriter.writerow ([getPDFContent ("/ home/nick/TAM_work/TAM_pdfs /"+ word) .encode ("ascii", "ignore")]) 을 가져 오십시오. – Matt

-1

나는 당신이 작은 변수에 많은 수를 넣었고 그 예외를 던졌습니다.

내가 당신에게 유니 코드와 매우 잘 작동 C#을 도구를 소개합니다, 당신은 귀하의 경우 http://unicode.codeplex.com

에서 찾을 수 있습니다 나는보다 위에있다)을

for i in range(0, pdf.getNumPages()): 

pdf.getNumPages을 (변경 운영자 추천 128 그냥 제어.

+0

-1 OP의 예외는 "작은 변수의 큰 숫자"로 막연하게 특성화 될 수있는 UnicodeEncodeError였으며 PDF 파일의 페이지 수와는 전혀 관련이 없습니다. 문서화되지 않은 "도구"에 관해서는 Python 사용자가 Python의 표준 유니 코드 기능 위에 무엇인가를 제공했음을 확신시켜야합니다. 그러나이 발언을 추가 스팸에 대한 초대장으로 사용하지 마십시오. –