簡體   English   中英

在python中使用UTF-16編碼

[英]Using UTF-16 encoding in python

我正在嘗試使用utf-16-le在python中編碼非ascii字符,這是此代碼的片段:

import os
import sys

def run():
    print sys.getdefaultencoding()
    reload(sys)
    sys.setdefaultencoding('utf-16-le')
    print sys.getdefaultencoding()
    test_dir = unit_test_utils.get_test_dir("utkarsh")
    dir_name_1 = '東京'
    ....
    ....

if __name__ == '__main__':
    run()

運行此代碼時,這是看到的錯誤:

# /u/bin/python-qs /root/python/tests/abc.py -c  /root/test.conf 
  File "/root/python/tests/abc.py", line 27
SyntaxError: Non-ASCII character '\xe6' in file /root/python/tests/abc.py on line 27, but no encoding declared; see http://www.python.org/peps/pep-0263.html for details

如何解決? 我嘗試將此行添加到文件的開頭,但無濟於事:

# -*- coding: utf-16-le -*-

這次的錯誤是:

# /u/bin/python-qs /root/python/tests/abc.py -c  /root/test.conf
  File "/root/python/tests/abc.py", line 2
    import os
import sys
...
...
if __name__ == '__main__':
    run()

    ^
SyntaxError: invalid syntax

編輯:

第27行:dir_name_1 ='東京'

在您顯示的代碼中,一切都差不多了。 您有一個以utf-8編碼的源文件(如您對file命令結果的注釋所述),因此該行

dir_name_1 = '東京'

實際上(當您使用Python 2.x時):

dir_name_1 = '\xe6\x9d\xb1\xe4\xba\xac' # utf8 for 東京

唯一的問題是,在第27行(您未顯示)上,您正在使用該utf8編碼的字符串做某事,可能試圖在未指定任何編碼的情況下將其(顯式或隱式)轉換為unicode,因此ascii被視為默認值和錯誤則正常,因為\\xe6不在ASCII范圍內。 您應該使用dir_name_1.decode('utf8')顯式解碼字符串

暫無
暫無

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

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