gpt4 book ai didi

python - Yaml 从文件中安全加载特殊字符 °

转载 作者:行者123 更新时间:2023-12-03 08:53:04 27 4
gpt4 key购买 nike

我正在尝试使用 PyYAML 读取 yml 配置文件。请参阅下面此类文件的示例。所需字段可能包含特殊字符,例如°。下面示例中的结果字符串不是所需的 °C,而是 °C

目标是仅读取°C。我可以控制配置文件,因此转义或引用不是问题。之后也可以进行解码、替换或其他操作,但它们也应该适用于没有特殊字符的字符串和具有其他特殊字符的字符串。

到目前为止,我在这条路上还没有取得成功。

示例

test.yml

super_important_variable: °C

代码

import yaml
with open('test.yml', 'r') as open_yml:
print(yaml.safe_load(open_yml))

当前结果

{'super_important_variable': '°C'}

期望的结果

{'super_important_variable': '°C'}

奇怪的是,这会返回正确的结果:

import yaml
yml_str = "super_important_variable: °C"
yaml.safe_load(yml_str)

> {'super_important_variable': '°C'}

最佳答案

试试这个:

import yaml
with open('test.yaml', 'r', encoding='utf-8') as open_yml:
print(yaml.safe_load(open_yml))

More here about encoding and files in python: Unicode (UTF-8) reading and writing to files in Python

关于python - Yaml 从文件中安全加载特殊字符 °,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57687058/

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