簡體   English   中英

如何將十六進制字符串轉換為日語並將其寫入Python 2.7中的文件?

[英]How to convert hex string into Japanese and write it to the file in Python 2.7?

我試圖將十六進制字符串轉換為日語(編解碼器:SHIFT-JIS),然后使用Python 2.7將日語輸出寫入文件。 但是,我所得到的只是文件中的原始十六進制字符串。 有人可以告訴我我做錯了什么嗎? 這是我使用的代碼:

fd = open(path,'w')
temp_str ='\x8d\xc5\x82\xe0\x8d\x82\x8b\x4d\x82\xc8\x89\xa4\x82\xc5\x82\xa0\x82\xc1\x82\xbd\x82\xbc\x81\x76\x80\x01\xff\xff'
fd.write(temp_str.encode('shift-jis'))
fd.close()

我在文件中得到的只是“ \\ x8d \\ xc5 \\ x82 \\ xe0 \\ x8d \\ x82 \\ x8b \\ x4d \\ x82 \\ xc8 \\ x89 \\ xa4 \\ x82 \\ xc5 \\ x82 \\ xa0 \\ x82 \\ xc1 \\ x82 \\ xbd \\ x82 \\ xbc \\ x81 \\ x76 \\ x80 \\ x01 \\ xff \\ xff”。

該字符串似乎是用UTF-16BE編碼的:

>>> print temp_str.decode('utf_16_be')
跅苠趂譍藶覤苅芠蓯芽芼腶老

但是它也似乎格式不正確,即被切成一半。 您應該首先通過解碼字節將字符串轉換為Unicode:

uni_str = temp_str.decode('utf_16_be')

然后將Unicode字符串保存到具有所需編碼的文件中:

fd = open(path,'w')
fd.write(uni_str.encode('shift-jis'))
fd.close()

但是,編解碼器“ shift-jis”似乎不喜歡您的字符串:

>>> print uni_str.encode('shift_jis')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'shift_jis' codec can't encode character u'\u8dc5' in position 0: illegal multibyte sequence

這不是日語,而是中文:

>>> print uni_str.encode('gb18030')
ڗ���f�G���B�i�[��ѿ�d�a�τ1�9

根據Python文檔 ,“ gb18030”是中文編解碼器。

是的,它是jiggebirsh,因為我沒有該編解碼器的終端,但是它是Python中唯一的一種編碼字符串的編碼編解碼器,除了UTF8 / 16/32之外沒有錯誤。

也許您應該以“ wb”而不是“ w”模式打開文件?

暫無
暫無

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

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