我正在使用一个计数器 from collections import Counter
,我想使用 matplotlib.pylot
打印它的值。
当我尝试使用:
plt.bar(range(len(cnt)), cnt.values(), align='center')
plt.xticks(range(len(cnt)), cnt.keys())
plt.show()
我收到以下错误:
ValueError: matplotlib display text must have all code points < 128 or use Unicode strings
这就是我尝试将 Counter 字典键转换为 Unicode 的原因。
最佳答案
如果您使用的是 Python 2.7,则可以使用字典理解:
unidict = {k.decode('utf8'): v.decode('utf8') for k, v in strdict.items()}
对于旧版本:
unidict = dict((k.decode('utf8'), v.decode('utf8')) for k, v in strdict.items())
(当然,这假设您的字符串是 UTF-8。)
关于python - 将 dict 的键和值从 str 转换为 Unicode 的最快方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16705274/