【问题标题】:How to encode/decode this file in Python?如何在 Python 中编码/解码这个文件?
【发布时间】: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


    【解决方案1】:

    您正在查看字节字符串值,打印为repr() 结果,因为它们包含在字典中。字符串表示可以重新用作 Python 字符串文字,并且使用字符串转义序列显示不可打印和非 ASCII 字符。容器值总是用repr() 表示以方便调试。

    因此,字符串 'K\xc3\xa4se' 包含两个具有十六进制值 C3 和 A4 的非 ASCII 字节,这是 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 的转义码,ä 字符。如果您希望将实际字符写入终端,请打印单个单词:

    print words['cheese']
    

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

    您可能想了解 Unicode 和 Python:

    【讨论】:

    • 谢谢,但我在发布之前已经尝试过了,但我没有将其视为解决方案,因为它仍然无法打印正确的字符。我的意思是我想看到 'ä' 而不是 '\xe4'。
    • @HerrActress:那么不要打印整个字典,打印单个单词。我解释了在打印容器时使用repr() 输出。
    • 是的,这有帮助!我对术语有点困惑。答案已接受
    【解决方案2】:

    你应该这样做。

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

    【讨论】:

      猜你喜欢
      • 2018-12-29
      • 2015-05-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-11
      • 1970-01-01
      • 2019-02-04
      • 1970-01-01
      相关资源
      最近更新 更多