【发布时间】:2013-07-20 11:25:06
【问题描述】:
我打算制作一个 Python 小游戏,它会从字典中随机打印键(英语),并且用户必须输入值(德语)。如果值正确,它会打印“正确”并继续。如果值错误,则打印“错误”并中断。
我认为这将是一项简单的任务,但我被困在了路上。我的问题是我不知道如何打印德语字符。假设我有一个包含此文本的文件“dictionary.txt”:
cat:Katze
dog:Hund
exercise:Übung
solve:lösen
door:Tür
cheese:Käse
我有这段代码只是为了测试输出的样子:
# -*- coding: UTF-8 -*-
words = {} # empty dictionary
with open('dictionary.txt') as my_file:
for line in my_file.readlines():
if len(line.strip())>0: # ignoring blank lines
elem = line.split(':') # split on ":"
words[elem[0]] = elem[1].strip() # appending elements to dictionary
print words
显然打印的结果与预期不符:
{'cheese': 'K\xc3\xa4se', 'door': 'T\xc3\xbcr',
'dog': 'Hund', 'cat': 'Katze', 'solve': 'l\xc3\xb6sen',
'exercise': '\xc3\x9cbung'}
那么我在哪里添加编码以及如何添加呢?
谢谢!
【问题讨论】:
标签: python python-2.7 unicode dictionary