ska*_*sie 2 python unicode dictionary python-2.7
我打算制作一个小 Python 游戏,它会从字典中随机打印键(英语),用户必须输入值(德语)。如果值正确,则打印“正确”并继续。如果值错误,则打印“错误”并中断。
我认为这将是一项简单的任务,但我被困在了路上。我的问题是我不知道如何打印德语字符。假设我有一个包含此文本的文件“dictionary.txt”:
cat:Katze
dog:Hund
exercise:Übung
solve:lösen
door:Tür
cheese:Käse
Run Code Online (Sandbox Code Playgroud)
我有这个代码只是为了测试输出的样子:
# -*- 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
Run Code Online (Sandbox Code Playgroud)
显然打印的结果并不像预期的那样:
{'cheese': 'K\xc3\xa4se', 'door': 'T\xc3\xbcr',
'dog': 'Hund', 'cat': 'Katze', 'solve': 'l\xc3\xb6sen',
'exercise': '\xc3\x9cbung'}
Run Code Online (Sandbox Code Playgroud)
那么我在哪里添加编码,我该怎么做呢?
谢谢!
您正在查看作为repr()结果打印的字节字符串值,因为它们包含在字典中。字符串表示可以作为 Python 字符串文字重新使用,不可打印和非 ASCII 字符使用字符串转义序列显示。容器值总是用 表示repr()以方便调试。
因此,字符串 'K\xc3\xa4se' 包含两个非 ASCII 字节,十六进制值为 C3 和 A4,这是 U+00E4 代码点的 UTF-8 组合。
您应该将值解码为unicode对象:
with open('dictionary.txt') as my_file:
for line in my_file: # just loop over the file
if line.strip(): # ignoring blank lines
key, value = line.decode('utf8').strip().split(':')
words[key] = value
Run Code Online (Sandbox Code Playgroud)
或者更好的是,codecs.open()在阅读文件时使用解码文件:
import codecs
with codecs.open('dictionary.txt', 'r', 'utf8') as my_file:
for line in my_file:
if line.strip(): # ignoring blank lines
key, value = line.strip().split(':')
words[key] = value
Run Code Online (Sandbox Code Playgroud)
打印生成的字典仍将使用repr()内容的结果,所以现在您将看到u'cheese': u'K\xe4se',因为\xe4Unicode 点 00E4 的转义码是ä字符。如果要将实际字符写入终端,请打印单个单词:
print words['cheese']
Run Code Online (Sandbox Code Playgroud)
但是现在您可以将这些值与您解码的其他数据进行比较,前提是您知道它们的正确编码,并操纵它们并将它们再次编码为您需要使用的任何目标编解码器。print将自动执行此操作,例如,在将 unicode 值打印到您的终端时。
您可能想阅读 Unicode 和 Python:
绝对最低要求每个软件开发人员绝对必须了解 Unicode 和字符集(没有任何借口!)作者:Joel Spolsky
内德巴切尔德的实用 Unicode
| 归档时间: |
|
| 查看次数: |
16731 次 |
| 最近记录: |