![](/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.