所以当我在python中使用“”、“”和“”时,我遇到了这个奇怪的问题。
我包括:#-编码: utf-8 --
在每个文件的顶部,并打印罚款,所以不用担心。然而,如果我做了len('æ')
,我得到了2。我正在做一个程序,我循环和分析丹麦语文本,所以这是一个大问题。下面是python终端的一些例子来说明这个问题:
In [1]: 'a'.islower()
Out[1]: True
In [2]: 'æ'.islower()
Out[2]: False
In [3]: len('a')
Out[3]: 1
In [4]: len('æ')
Out[4]: 2
In [5]: for c in 'æ': print c in "æøå"
True
True
In [6]: print "æøå are troublesome characters"
æøå are troublesome characters
我可以通过简单地执行c.islower() or c in "æøå"
来检查c是否是小写字母,但正如上面所示,islower()和isupper()不工作于‘’、‘’和‘’“的问题,但正如上面所示,”的两个部分将被计算为小写,并被计算为“双倍”。
有什么办法能让这些信和其他信件一样吗?
我在windows 10上运行python2.7,使用冠层作为一种简单的方法来获得我需要的滑雪和numpy。
发布于 2017-03-07 13:40:15
在python 2中,您无意中发现了字符串是字节的问题。对于头# --编码: utf-8 --您只告诉解释器您的源代码是utf-8,但这对字符串的处理没有影响。
解决问题的方法是使用decode方法将所有字符串转换为unicode对象,例如
danish_text_raw = 'æ' # here you would load your text
print(type(danish_text_raw)) # returns string
danish_text = danish_text_raw.decode('utf-8')
print(type(danish_text)) # returns <type 'unicode'>
这样就可以解决这个问题了。确保程序中使用的所有字符串都是unicode,而不是字节对象。否则,比较可能导致奇怪的结果。例如
danish_text_raw == danish_text # this yields false
要确保使用unicode字符串,可以使用此函数来确保
def to_unicode(in_string):
if isinstance(in_string,str):
out_string = in_string.decode('utf-8')
elif isinstance(in_string,unicode):
out_string = in_string
else:
raise TypeError('not stringy')
return out_string
https://stackoverflow.com/questions/42649280
复制相似问题