关于 utf8 字符的 Python 输出的解释

Interpretation of Python Output regarding utf8 characters

我有一个 .txt 文件,我需要计算其中所有字符的频率,以便对我的密码学练习进行简单的频率分析。

我认为代码运行良好,但 Python 似乎无法读取 Ä、Ö、ß 等字符(德语字母表)。由于代码正在读取 .txt 文件,我假设它是 utf8 格式。

这是输出:

Counter({' ': 168, 'S': 136, '\xc3': 103, 'Z': 83, 'G': 80, 'P': 80,
'W': 76, 'J': 66, 'O': 63, 'Q': 62, 'R': 57, 'U': 57, 'L': 47, '\x84': 43,
'K': 39, '\x9c': 28, 'X': 25, 'A': 23, 'C': 22, '\x9f': 18, 'E': 17, 'N':
17, '\x96': 14, ',': 11, 'D': 8, 'Y': 8, 'T': 6, 'V': 6, 'B': 5, '"': 4,
"'": 3, 'F': 2, 'M': 2, '!': 1, '-': 1, '?': 1}) [Finished in 0.1s]

我的问题是如何解释'\xc3'等反斜杠字符。我在网上找不到任何关于如何翻译的内容?

编辑(我的代码):

from collections import Counter
with open('/Users/StB/Downloads/text.txt') as f:
    c = Counter()
    for x in f:
        c += Counter(x.strip())
print c

编辑 2:

新输出:

Counter({' ': 168, 'S': 136, 'Z': 83, 'P': 80, 'G': 80, 'W': 76, 'J': 66, 'O': 63, 'Q': 62, 'R': 57, 'U': 57, 'L': 47, 'Ä': 43, 'K': 39, 'Ü': 28, 'X': 25, 'A': 23, 'C': 22, 'ß': 18, 'N': 17, 'E': 17, 'Ö': 14, ',': 11, 'Y': 8, 'D': 8, 'T': 6, 'V': 6, 'B': 5, '"': 4, "'": 3, 'F': 2, 'M': 2, '-': 1, '!': 1, '?': 1})

新代码:

from collections import Counter
with open('/Users/StB/Downloads/text.txt', encoding= 'utf - 8') as f:
    c = Counter()
    for x in f:
        c += Counter(x.strip())
print (c)

endcoding 不适用于我在 sublime text 上使用的 运行 版本。虽然在 IDLE 中工作得很好!

在 Python 2 的情况下,您需要将正在读取的字符串显式解码为 Unicode。您还可以使用 Counter.update 方法来避免创建和丢弃 Counter 个对象。

from collections import Counter
with open('/Users/StB/Downloads/text.txt') as f:
    c = Counter()
    for x in f:
        c.update(x.decode('utf-8').strip())
print c