Skip to main content
 首页 » 编程设计

python之将所有 Unicode 字符视为单个字母

2025年05月04日15mayingbao

我想创建一个程序来计算单词的“值”,方法是根据字母在单词中的第一个位置添加赋予字母的值(作为练习,我是 Python 新手)。
IE。 "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 代码)。有没有办法绕过它并让解释器将所有字母视为单个字母?

请您参考如下方法:

将输入解码为 un​​icode,然后在所有地方使用 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 运行它。

更多信息,请阅读这篇非常有用的文章talk on the subject