2012-05-25 42 views
2

Possible Duplicate:
Converting a latin string to unicode in pythonunicode字符串轉換爲原始格式

我有以下格式列表中文件

list_example = [ 
     u"\u00cdndia, Tail\u00e2ndia & Cingapura", 
     u"Lines through the days 1 (Arabic) \u0633\u0637\u0648\u0631 \u0639\u0628\u0631 \u0627\u0644\u0623\u064a\u0627\u0645 1", 
] 

但在列表中的字符串的實際格式存儲之後

actual_format = [ 
     "Índia, Tailândia & Cingapura ", 
     "Lines through the days 1 (Arabic) سطور عبر الأيام 1 | شمس الدين خ " 
] 

如何將list_example中的字符串轉換爲actual_format列表中的字符串?

+1

格式已經是正確的.. 。嘗試'print list_example [1]' – JBernardo

+0

注意:您需要將'.encode()'list_example [1]'編碼爲終端可以識別的編碼,具體取決於您的區域設置。 – geoffspear

+0

但是當我嘗試 –

回答

2

你的問題對我有點不清楚。無論如何,以下指南應該可以幫助您解決您的問題。

如果定義在Python源代碼的字符串,那麼你應該

  • 知道在哪個字符編碼編輯器保存的源代碼文件(例如,UTF-8)
  • 宣佈在該編碼你的源文件的第一行,通過例如# -*- coding: utf-8 -*-
  • 定義這些字符串作爲Unicode對象:

strings = [u"Índia, Tailândia & Cingapura ", u"Lines through the days 1 (Arabic) سطور عبر الأيام 1 | شمس الدين خ "]

(注:在Python 3,文字串默認情況下使用Unicode對象,即你不需要u在Python 2。 Unicode字符串是unicode型的,在Python 3,Unicode字符串是string型)

當你再要這些字符串保存到一個文件,你應該明確地定義字符編碼:

with open('filename', 'w') as f: 
    s = '\n'.join(strings) 
    f.write(s.encode('utf-8')) 

當你那麼想從該文件中再次讀取這些字符串,你又要爲了明確定義的字符編碼文件內容的正確解碼:

with open('filename') as f: 
    strings = [l.decode('utf-8') for line in f] 
+1

如果涉及unicode,您應該使用'codecs'模塊寫入/讀取文件。例如'用codecs.open('test',encoding ='utf-8',mode ='w')'。有關詳細信息,請參閱Unicode HOWTO:http://docs.python.org/howto/unicode.html – schlamar

+0

是的,這是一個非常方便的模塊。然而,我的回答的目標是溼婆掌握編碼/解碼要領。因此,我不會修改答案,好嗎? :) –

1
actual_format = [x.decode('unicode-escape') for x in list_example] 
+0

但是,當我運行上述命令我得到follwing錯誤「UnicodeEncodeError:'ascii'編解碼器不能編碼字符u'\ xcd'在位置0:序號不在範圍內(128) 「 –