2016-12-14 77 views
-1

我無法正確編碼和解碼包含單引號和雙引號的字符串。注意:我需要顯示引號。帶引號的編碼/解碼字符串

我將以下字符串保存在txt文件中。

Here’s their mantra: 「Eat less and exercise more. The secret to weight loss is energy balance. There are no good or bad calories. It’s all about moderation.」 

with open ("file.txt", "r") as myfile: 
    data = myfile.read() 
    myfile.close() 

print data 
the result: 
 
HereΓÇÖs their mantra: ΓÇ£Eat less and exercise more. The secret to weight loss is energy balance. There are no good or bad calories. ItΓÇÖs all about moderation.ΓÇ¥ 

我完全可以省略引號,但我需要向他們展示

print data.decode('ascii', 'ignore') 

Heres their mantra: Eat less and exercise more. The secret to weight loss is energy balance. There are no good or bad calories. Its all about moderation. 

print json.dumps(data) 

"\ufeff\nHere\u2019s their mantra: \u201cEat less and exercise more. The secret to weight loss is energy balance. There are no good or bad calories. It\u2019s all about moderation.\u201d " 
+0

您的控制檯或終端編碼不支持UTF-8(輸入文件的編碼)。您的控制檯改爲使用cp437。 –

+0

那麼,我該怎麼做? –

+2

你在做什麼?您的控制檯編碼不支持文本中的「花哨」引號;你可以用ASCII等價物替換它們,或者你可以改變你的控制檯編碼。 –

回答

2

你的文件不是ASCII。你似乎意識到這一點,因爲你明確地告訴它忽略解碼錯誤。

它看起來像文件是UTF-8,Python正在打印unicode對象的UTF-8編碼,然後Windows通過控制檯的默認代碼頁進行解釋(在我的系統上,cp437,一個ASCII超集提供了一堆控制檯繪圖符號作爲字符)。要解決,正確地對其進行解碼:或者

print data.decode('utf-8') 

,您可以使用Python 3 open功能,即使在Python 2.7,通過導入io和使用io.open,這將讓您指定的編碼,並自動爲你執行的解碼並無縫地:

from __future__ import print_function # Including the __future__ import makes 
             # this 100% Py2/Py3 compatible 
import io 

with io.open("file.txt", encoding="utf-8") as myfile: 
    data = myfile.read() 
print(data) 

如果您使用的是Windows,命令提示符可能不會支持任意的Unicode輸出不幸的是,並沒有100%的解決方案,但運行

chcp 65001 

在您的cmd.exe提示符之前啓動Python程序將使它使用UTF-8作爲控制檯的「代碼頁」(它如何解釋Python輸出的原始字節)。該代碼頁有一些錯誤(搜索瞭解更多),但它是最接近您將得到的。您還需要Unicode友好控制檯字體,more details here

手動代碼頁操作的替代解決方案(或轉移到Python 3.6,它完全繞過代碼頁問題)是使用像unidecode這樣的包將非ASCII字符轉換爲它們的ASCII等效字符(因此Unicode智能引號變爲純ASCII直引號)。關於在其他地方使用unidecode的信息有很多,我會避免在這裏迴流。

+0

問題仍然存在。 –

+0

在哪一個你會得到一個UnicodeEncodeError,因爲他們的控制檯配置爲CP437。 –

+0

@AnayBose:不,你現在得到一個*不同*的錯誤。這不是同一個問題。 –