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

标签 python yaml pyyaml

我正在尝试使用 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/

相关文章:

php - 我可以在子文件夹中组织 Doctrine YAML 映射吗?

python - 在python中读取yaml文件时如何跳过行?

python - Pyyaml - 对键、整数和字符串使用不同的样式

python-2.7 - PyYAML - 列表的顺序是否保留?

python - 如何在文件中写入 YAML 格式的数据?

python - 在Python中调用citeparser函数

python - 解析txt文件并将数据存储到字典中

java - 使用 Spring REST 端点提供 yaml 文件

python - 如何对 pandas.Series 列进行二进制分解

python - 在 Python 中使用 Rpy2 对具有翻转坐标的 ggplot2 条形图进行排序