簡體   English   中英

如何打開帶有 utf-8 非編碼字符的文件?

[英]How to open a file with utf-8 non encoded characters?

我想在 python 中打開一個文本文件 (.dat),我收到以下錯誤:'utf-8' codec can't decode byte 0x92 in position 4484: invalid start byte but the file is encoding using utf-8, so也許有一些無法讀取的字符。 我想知道,有沒有辦法在不調用每個奇怪字符的情況下處理問題? 因為我有一個相當大的文本文件,我需要幾個小時才能找到非編碼的 Utf-8 編碼字符。

這是我的代碼

import codecs
f = codecs.open('compounds.dat', encoding='utf-8')
for line in f:
    if "InChI=1S/C11H8O3/c1-6-5-9(13)10-7(11(6)14)3-2-4-8(10)12/h2-5" in line:
        print(line)
searchfile.close()

找到壞字節不應該“花你幾個小時”。 該錯誤會告訴您它的確切位置; 它位於您輸入中的索引 4484 處,值為0x92 如果你這樣做:

with open('compounds.dat', 'rb') as f:
    data = f.read()

無效字節將在data[4484] ,您可以根據需要進行切片以找出它周圍的內容。

無論如何,如果您只想忽略或替換無效字節,這就是errors參數的用途。 使用io.open (因為codecs.open在很多方面codecs.open被巧妙地破壞了,而io.open更快更正確):

# If this is Py3, you don't even need the import, just use plain open which is
# an alias for io.open
import io

with io.open('compounds.dat', encoding='utf-8', errors='ignore') as f:
    for line in f:
        if u"InChI=1S/C11H8O3/c1-6-5-9(13)10-7(11(6)14)3-2-4-8(10)12/h2-5" in line:
            print(line)

只會忽略無效字節(丟棄它們,就好像它們從未存在過一樣)。 您還可以通過errors='replace'為每個垃圾字節插入一個替換字符,這樣您就不會默默地丟棄數據。

如果處理大量數據,最好將編碼用作默認值,如果錯誤仍然存​​在,則也使用 errors="ignore"

with open("filename" , 'r'  , encoding="utf-8",errors="ignore") as f:
    f.read()

暫無
暫無

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

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