我有这个功能:
#!/usr/bin/python
# coding=UTF-8
def filt(word):
dic = {'á':'a','é':'e','í':'i','ó':'o','ú':'u'}
new = ''
for l in word:
new = new + dic[l]
return new
但是当我为某些字符串(例如“árvore”)调用该函数并运行脚本时,我得到以下结果:
Traceback (most recent call last): File "filt.py", line 11, in print filt("árvore") File "filt.py", line 8, in filt new = new + dic[l] KeyError: '\xc3'
出了什么问题?
最佳答案
您应该将单词作为 unicode 对象传递,因此迭代是在每个 unicode 字符上完成的:
def filt(word):
dic = {u'á':'a', u'é':'e', u'í':'i', u'ó':'o', u'ú':'u'}
new = ''
for l in word:
new = new + dic.get(l, l)
return new
print(filt(u"árvore"))
# ^
# arvore
或者在迭代字符串之前使用word.decode('utf8')
。
记住也要更新您的字典键,并使用 dict.get
返回不是字典键的项目的原始对象。
关于python - 使用非 ASCII 字符作为 python 字典中的键时出现 KeyError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42297801/