2016-12-14 78 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:不,你现在得到一个*不同*的错误。这不是同一个问题。 –