gpt4 book ai didi

python - 在 Python 中使用 for 循环丢失重音

转载 作者:行者123 更新时间:2023-11-28 22:52:38 25 4
gpt4 key购买 nike

当我在 Python 中使用下一段代码时:

line = "áaáaáaá"
for c in line:
print c

我的观点是:

� � A � � A � � A � �

我该如何解决这个问题?

最佳答案

我用谷歌搜索了一下这个问题,我在这里找到了一些东西:

http://eclipsesource.com/blogs/2013/02/21/pro-tip-unicode-characters-in-the-eclipse-console/

尝试从 Launch Configuration 对话框 > Common > 将编码设置为 utf-8latin-1

如果这不能解决问题,请尝试将每个字符转换为 utf-8 格式,然后打印:

line = unicode("áaáaáaá", encoding="utf-8")
for c in line:
print c

编辑:这里有一些解释:)

当您未将编码指定为 utf-8 时,解释器会将其分解为错误的部分。例如,à 存储为 '\xc3\xa1`。在循环中,python 认为它是两个独立的字符:

>>> s = "áaáaáaá".encode()
>>> for i, c in enumerate(s):
print(i,c)


0 195
1 161
2 97
3 195
4 161
5 97
6 195
7 161
8 97
9 195
10 161

它认为 \xc3\xa1 是两个字符,即:

Ã
¡

那么,为什么当您指定编码时它会起作用?好吧,我相信你已经明白了。当您将编码设置为utf-8时,它会将字符串视为格式为utf-8,并且它知道\xc3\xa1 是一个字符。

好吧,在我的第二种方法中,即使您不将编码设置为 utf-8,它也能正常工作。为什么?因为:

line = unicode("áaáaáaá", encoding="utf-8")

将编码从 utf-8 转换为您的解释器使用的编码。

希望这对您有所帮助!

关于python - 在 Python 中使用 for 循环丢失重音,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20300329/

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