从特殊字符列表创建字典

Mac*_*ers 0 python dictionary sorteddictionary

我正在研究这个小脚本:基本上它将列表元素(包含特殊字符)映射到其索引以创建字典.

#!/usr/bin/env python
#-*- coding: latin-1 -*-

ln1 = '?0>9<8~7|65"4:3}2{1+_)'
ln2 = "(*&^%$£@!/`'\][=-#¢"

refStr = ln2+ln1

keyDict = {}
for i in range(0,len(refStr)):
    keyDict[refStr[i]] = i


print "-" * 32
print "Originl: ",refStr
print "KeyDict: ", keyDict

# added just to test a few special characters
tsChr = ['£','%','\\','¢']

for k in tsChr:
    if k in keyDict:
        print k, "\t", keyDict[k]
    else: print k, "\t", "not in the dic."
Run Code Online (Sandbox Code Playgroud)

它返回如下结果:

Originl:  (*&^%$£@!/`'\][=-#¢?0>9<8~7|65"4:3}2{1+_)
KeyDict:  {'!': 9, '\xa3': 7, '\xa2': 20, '%': 4, '$': 5, "'": 12, '&': 2, ')': 42, '(': 0, '+': 40, '*': 1, '-': 17, '/': 10, '1': 39, '0': 22, '3': 35, '2': 37, '5': 31, '4': 33, '7': 28, '6': 30, '9': 24, '8': 26, ':': 34, '=': 16, '<': 25, '?': 21, '>': 23, '@': 8, '\xc2': 19, '#': 18, '"': 32, '[': 15, ']': 14, '\\': 13, '_': 41, '^': 3, '`': 11, '{': 38, '}': 36, '|': 29, '~': 27}
Run Code Online (Sandbox Code Playgroud)

这是所有好的,除了字符£,%并且\被转换成\xa3,\xa2\\分别.有没有人知道为什么打印ln1/ ln2很好但字典不是.我怎样才能解决这个问题?任何帮助非常感谢.干杯!!


更新1

我已经添加了额外的特殊字符- # 和¢,然后这是我得到以下@邓肯的建议:

! 9
? 7
? 20
% 4
$ 5
....
....
8 26
: 34
= 16
< 25
? 21
> 23
@ 8
? 19
....
....
Run Code Online (Sandbox Code Playgroud)

请注意第7,19和20个元素,它们根本无法正确打印.第21个元素是实际的?字符.干杯!!


更新2

刚刚将这个循环添加到我的原始帖子中以实际测试我的目的:

tsChr = ['£','%','\\','¢']
for k in tsChr:
    if k in keyDict:
        print k, "\t", keyDict[k]
    else: print k, "\t", "not in the dic."
Run Code Online (Sandbox Code Playgroud)

这就是我得到的结果:

£   not in the dic.
%   4
\   13
¢   not in the dic.
Run Code Online (Sandbox Code Playgroud)

惠斯特运行脚本,它认为£并且¢实际上不在字典中 - 这是我的问题.任何人都知道如何解决这个问题或者我做错了什么/在哪里?

最终,我会检查从字典中的文件(或文本行)的字符(县),看它是否存在,存在具有人物像的机会,é£等文本.干杯!!

Dun*_*can 6

当您打印包含字符串的字典或列表时,Python将显示repr()字符串.如果您print repr(ln2)发现没有任何变化:您的字典键只是'£'和c的latin-1编码.字符.

如果你这样做:

for k in keyDict:
    print k, keyDict[k]
Run Code Online (Sandbox Code Playgroud)

然后字符将按预期显示.