提问人:Stine Nyhus 提问时间:3/26/2023 最后编辑:TomerikooStine Nyhus 更新时间:3/26/2023 访问量:179
如何使 Python 将文字字符串视为 UTF-8 编码的字符串 [duplicate]
How to make Python treat literal string as UTF-8 encoded string [duplicate]
问:
我从文件中加载了一些 Python 字符串。它们看起来像列表,但实际上是字符串,例如:
example_string = '["hello", "there", "w\\u00e5rld"]'
我可以轻松地将其转换为实际的字符串列表:
def string_to_list(string_list:str) -> List[str]:
converted = string_list.replace('"', '').replace('[', '').replace(']', '').split(',')
return [s.strip() for s in converted]
as_list = string_to_list(example_string)
print(as_list)
这将返回以下字符串列表: 问题在于字符串最后一个元素的编码。我跑步时看起来像这样,但是如果我跑步["hello", "there", "w\\u00e5rld"]
print(as_list)
for element in as_list:
print(element)
它返回
hello
there
w\u00e5rld
我不知道第一个反斜杠会发生什么,在我看来,它似乎是为了逃避编码中的第二个反斜杠。如何让 Python 只解析 UTF-8 字符并打印“wørld”?问题是它是一个字符串,而不是编码,所以不起作用。as_list[2].decode("UTF-8")
我尝试使用 string.decode(),并尝试纯打印
答:
1赞
ShadowRanger
3/26/2023
#1
将其解码为字符串的正确方法不是您正在执行的一组疯狂的字符串操作。它只是 ast.literal_eval(example_string),
它可以很好地处理 Unicode 转义:list
import ast
example_string = '["hello", "there", "w\\u00e5rld"]'
example_list = ast.literal_eval(example_string)
for word in example_list:
print(word)
假设您对字符有适当的字体支持,则输出:
hello
there
wårld
如果您绝对需要修复 Unicode 转义,则可以使用 codecs
模块进行unicode_escape
解码,但在这种情况下,您在字符串中有一个合法的 Python 文本,并且可以完成所有工作。ast.literal_eval
评论
0赞
Mark Tolonen
3/26/2023
在本例中,字符串可能是用 . -> . 当字符串是单引号和非 JSON 时,通常需要它。json.dumps
ensure_ascii=True
json.loads(example_string)
['hello', 'there', 'wårld']
ast.literal_eval
0赞
ShadowRanger
3/26/2023
@MarkTolonen:没错,任何一个都可以。 更快的 IIRC,假设输入是有保证的 JSON,这比 Python 文字更受限制。json.loads
评论
ast
codecs
"w\\u00e5rld".encode('latin-1', 'backslashreplace').decode('unicode-escape')
codecs.decode("w\\u00e5rld", 'unicode-escape')
codecs
.decode
str