![](/img/trans.png)
[英]python and ipython seem to treat unicode characters differently
[英]Treat all Unicode characters as single letters
我想创建一个程序来计算单词的“值”,方法是根据单词在单词中的第一个位置添加给单词的值(作为练习,我是Python的新手)。
就是 "foo"
将返回5(因为“ f” = 1,“ o” = 2), "bar"
将返回6(因为“ b” = 1,“ a” = 2,“ r” = 3)。
到目前为止,这是我的代码:
# -*- coding: utf-8 -*-
def ppn(word):
word = list(word)
cipher = dict()
i = 1
e = 0
for letter in word:
if letter not in cipher:
cipher[letter] = i
e += i
i += 1
else:
e += cipher[letter]
return ''.join(word) + ": " + str(e)
if __name__ == "__main__":
print ppn(str(raw_input()))
它的效果很好,但是对于包含“ł”,“±”等字符的单词,它不会返回正确的值(我想这是因为它首先将这些字母转换为Unicode代码)。 有没有一种方法可以绕过它,并使口译员将所有字母视为单个字母?
将输入解码为unicode,然后在各处使用unicode,然后在输出时解码。
具体来说,您需要进行更改
print ppn(str(raw_input()))
至
print ppn(raw_input().decode(sys.stdin.encoding))
这将解码您的输入。 然后,您还需要更改
''.join(word) + ": " + str(e)
至
u''.join(word) + u': ' + unicode(e)
这使您的所有代码在内部都使用unicode对象。
Print可以将unicode正确编码为您的终端使用的任何编码,但是您也可以根据需要指定它。
另外,您也可以执行已完成的操作,但是可以使用python 3运行它。
用shell的编码解码:
if __name__ == "__main__":
import sys
print ppn((raw_input()).decode(sys.stdin.encoding))
对于Unix系统,通常使用UTF-8
。 在Windows上,情况可能有所不同。 要保存,请使用sys.stdin.encoding
。 您永远不知道脚本将在哪里运行。
或者,甚至更好。 切换至Python 3:
# -*- coding: utf-8 -*-
import sys
assert sys.version_info.major > 2
def ppn(word):
word = list(word)
cipher = dict()
i = 1
e = 0
for letter in word:
if letter not in cipher:
cipher[letter] = i
e += i
i += 1
else:
e += cipher[letter]
return ''.join(word) + ": " + str(e)
if __name__ == "__main__":
print(ppn(str(input())))
在Python 3中,默认情况下,字符串是unicode。 因此,无需解码业务。
到目前为止,所有答案都说明了该怎么做,但并没有说明正在进行的事情,因此这里有一些提示。
在Python 2中使用raw_input()
,将返回一个字节字符串input()
Python 3上的input()
表现不同)。 大多数unicode字符不能表示为单个字节,原因是unicode字符比可以用字节表示的值多。
当使用utf-8或其他编码对ł
或ą
类的字符进行编码时,可能需要两个字节或更多个字节:
>>> 'ł'
'\xc5\x82'
>>> 'ą'
'\xc4\x85'
您的原始程序将这两个字节解释为不同的字符,从而导致错误的结果。
Python提供了一种替代字节字符串的方法:unicode字符串。 使用unicode字符串,一个字符与一个字符完全一样(字符串的内部表示是不透明的)出现,并且不会出现您遇到的问题。
因此,将字节字符串解码为unicode字符串是正确的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.