如何在Python中编码/解码此文件?

时间:2013-07-20 11:25:06

标签: python python-2.7 unicode dictionary

我打算制作一个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'}

那么我在哪里添加编码呢?我该怎么做?

谢谢!

2 个答案:

答案 0 :(得分:2)

您正在查看字节字符串值,打印为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

或更好的是,在阅读文件时使用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

打印生成的字典仍将使用repr()结果作为内容,因此现在您将看到u'cheese': u'K\xe4se',因为\xe4是Unicode点00E4的转义码,{ {1}}角色。如果您希望将实际字符写入终端,请打印单个单词:

ä

但现在您可以将这些值与您解码的其他数据进行比较,只要您知道它们的正确编码,并对它们进行操作并将它们再次编码为您需要使用的 target 编解码器。 print words['cheese'] 会自动执行此操作,例如,在将unicode值打印到终端时。

您可能想要阅读Unicode和Python:

答案 1 :(得分:-1)

这就是你应该怎么做的。

def game(input,answer):
       if input == answer:
             sentence = "You got it!"
             return sentence
       elif input != answer:
               wrong = "sorry, wrong answer"
               return wrong