gpt4 book ai didi

python - 如何在Python中编码/解码这个文件?

转载 作者:太空宇宙 更新时间:2023-11-03 18:53:33 25 4
gpt4 key购买 nike

我计划制作一个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'}

那么我应该在哪里添加编码以及如何添加呢?

谢谢!

最佳答案

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

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

您可能想阅读有关 Unicode 和 Python 的内容:

关于python - 如何在Python中编码/解码这个文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17761741/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com