不幸的是,雖然有些軟件包可以通過分析文檔的內容做出很好的猜測,但確定純文本文檔的編碼方式並不是一成不變的。一種流行的編碼檢測第三方模塊是chardet。或者你可以手動使用一些流行的編碼進行試驗和錯誤,看看有什麼作用。
確定正確的編碼後,替換操作本身在Python 3中很簡單。核心思想是將編碼傳遞給open
函數,以便可以將Unicode字符串對象寫入文件或讀取來自文件的Unicode字符串對象。這是一個簡短的演示。如果您的終端的編碼設置爲UTF-8,這將正確工作。我已經在Python 3.6.0上進行了測試,包括Bash shell和idle3.6。
fname = 'test.txt'
encoding = 'cp1252'
data = 'This is some Random text 「^char」: for testing\n'
print(data)
# Save the text to file
with open(fname, 'w', encoding=encoding) as f:
f.write(data)
# Read it back in
with open(fname, 'r', encoding=encoding) as f:
text = f.read()
print(text, text == data)
# Perform the replacement
target = 'Random text 「^char」:'
out = text.replace(target, 'XXX')
print(out)
輸出
This is some Random text 「^char」: for testing
This is some Random text 「^char」: for testing
True
This is some XXX for testing
哪個Python版本您使用的?在與編碼問題有關的問題中提及這一點非常重要,因爲Python 2和Python 3在處理Unicode方面存在很大差異。 –
我不認爲你的文檔使用ISO-8859-1,因爲該編碼沒有''''或''''。但是,如Windows維基百科關於[Windows-1252]的文章中所述,(https://en.wikipedia.org/wiki/Windows-1252)將Windows代碼頁1252編碼的文本標記爲ISO-8859-1非常常見)。 –
我正在使用Python 3.6.0。我如何知道文檔使用的實際編碼?有一種方法可以讓角色粘貼到我的腳本中,一旦我知道它的確是什麼? –