簡體   English   中英

Python編碼\\解碼,用於寫入文本文件

[英]Python Encoding\Decoding for writing to a text file

老實說,我已經花了很多時間,而且它正在慢慢殺死我。 我已經從PDF中剝離了內容,並將其存儲在數組中。 現在,我試圖將其拉出陣列,然后將其寫入txt文件。 但是,由於編碼問題,我似乎無法實現這一目標。

allTheNTMs.append(contentRaw[s1:].encode("utf-8"))
for a in range(len(allTheNTMs)):
        kmlDescription = allTheNTMs[a]
        print kmlDescription #this prints out fine
        outputFile.write(kmlDescription)

我得到的錯誤是“ unicodedecodeerror:ASCII編解碼器無法解碼位置213中的字節0xc2:常規不在范圍內(128)。

我現在只是在弄亂,但是我嘗試了各種方法來使這些東西寫出來。

outputFile.write(kmlDescription).decode('utf-8')          

如果這是基礎知識,請原諒我,我仍在學習Python(2.7)。

干杯!

EDIT1:示例數據如下所示:

Chart 3686 (plan, Morehead City) [ previous update 4997/11 ] NAD83 DATUM
Insert the accompanying block, showing amendments to coastline,
depths and dolphins, centred on: 34° 41´·19N., 76° 40´·43W.
Delete R 34° 43´·16N., 76° 41´·64W.

當我添加打印類型(原始)時,我得到

編輯2:當我只是嘗試寫入數據時,我收到原始錯誤消息(ascii編解碼器無法解碼字節...)

我將檢查建議的主題和視頻。 謝謝大家!

編輯3:我正在使用Python 2.7

編輯4:當agf注意到我正在雙重編碼時,他在下面的評論中碰到了頭。 我嘗試過對以前一直有效的字符串進行雙重編碼,並產生了最初拋出的錯誤消息。 就像是:

text = "Here's a string, but imagine it has some weird symbols and whatnot in it - apparently latin-1"
textEncoded = text.encode('utf-8')
textEncodedX2 = textEncoded.encode('utf-8')
outputfile.write(textEncoded) #Works!
outputfile.write(textEncodedX2) #failed

一旦確定要進行雙重編碼,解決方案如下:

allTheNTMs.append(contentRaw[s1:].encode("utf-8"))
for a in range(len(allTheNTMs)):
    kmlDescription = allTheNTMs[a]
    kmlDescriptionDecode = kmlDescription.decode("latin-1")
    outputFile.write(kmlDescriptionDecode)

它現在正在運行,我非常感謝您的所有幫助!!

我的猜測是您打開的輸出文件已使用latin1甚至utf-8編解碼器打開,因此您無法將utf-8編碼的數據寫入該文件,因為它會嘗試將其轉換,否則將其寫入一個正常打開的文件任何任意數據字符串,這是一個重新創建類似錯誤的示例

u = u'सच्चिदानन्द हीरानन्द वात्स्यायन '
s = u.encode('utf-8')
f = codecs.open('del.text', 'wb',encoding='latin1')
f.write(s)

輸出:

Traceback (most recent call last):
  File "/usr/lib/wingide4.1/src/debug/tserver/_sandbox.py", line 1, in <module>
    # Used internally for debug sandbox under external interpreter
  File "/usr/lib/python2.7/codecs.py", line 691, in write
    return self.writer.write(data)
  File "/usr/lib/python2.7/codecs.py", line 351, in write
    data, consumed = self.encode(object, self.errors)
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe0 in position 0: ordinal not in range(128)

解決方案

如果您沒有設置任何編解碼器,這將起作用

f = open('del.txt', 'wb') 
f.write(s)

如果已經使用正確的編解碼器打開了outputFile,則另一個選擇是直接寫入文件而不對Unicode字符串進行編碼,例如

f = codecs.open('del.text', 'wb',encoding='utf-8')
f.write(u)

您的錯誤消息似乎與您的任何Python語法都不相關,但實際上您正在嘗試解碼在UTF-8中沒有等效值的十六進制值。

十六進制0xc2似乎代表拉丁字符-大寫A,頂部帶有重音符號。 因此,不要使用“ allTheNTMs.append(contentRaw [s1:]。encode(” utf-8“))” ,請嘗試:

allTheNTMs.append(contentRaw[s1:].encode("latin-1"))

我不是Python專家,因此這可能無法正常工作,但您似乎正在嘗試編碼拉丁字符。 鑒於您也收到了錯誤消息,因此似乎在嘗試使用UTF-8進行編碼時,Python只會瀏覽前128個條目,因為您的錯誤似乎表明條目“ 0Xc2”超出了范圍,而實際上這是在UTF-8的前128個條目中。

暫無
暫無

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

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