我試圖轉換一個包含中文字符的漢化字符轉換成latin1編碼的本地化文件。用Python編碼中文到Latin1的字符編碼
然而,當我運行python腳本我得到這個錯誤...
UnicodeDecodeError: 'ascii' codec can't decode byte 0xb9 in position 0: ordinal not in range(128)
這裏是我的Python腳本,它本質上只是需要用戶輸入轉換所述文件。然後轉換文件(所有以[[或者爲空]開頭的行都應該跳過)...需要轉換的部分始終位於列表中的索引1處。
# coding: utf8
# Enter File Name
file_name = raw_input('Enter File Path/Name To Convert: ')
# Open the File we Write too...
write_file = open(file_name + "_temp", 'w+')
# Open the File we Read From...
read_file = open(file_name)
with open(file_name) as file_to_write:
for line in file_to_write:
# We ignore any line that starts with [] or is empty...
if line and line[0:1] != '[':
split_string = line.split("=")
if len(split_string) == 2:
write_file.write(split_string[0] + "=" + split_string[1].encode('gbk').decode('latin1') + "\n")
else:
write_file.write(line)
else:
write_file.write(line)
# Close File we Write too..
write_file.close()
# Close File we read too..
read_file.close()
並且例如配置文件是...
[Example]
Password=密碼
輸出應被轉換爲...
[Example]
Password=±K½X
http://www.joelonsoftware.com/articles/Unicode.html <在這裏閱讀。它有助於 – jsbueno