You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中让PyYAML保留带尾零的版本号为字符串?

解决PyYAML解析版本号丢失末尾0的问题

问题复现

example.yaml

version: 0.20

main.py

import yaml

with open("example.yaml", "r") as stream:
    try:
        print(yaml.safe_load(stream))
    except yaml.YAMLError as exc:
        print(exc)

实际输出

{'version': 0.2}

期望输出

{'version': '0.20'}

PyYAML会将version字段解析为浮点数,导致末尾的0被自动省略。我们需要在Python代码内处理该问题,无需修改原YAML文件。

代码内解决方案

通过自定义PyYAML的安全加载器,重载浮点数的解析逻辑,将带有末尾0的小数格式标量保留为字符串:

import yaml
from yaml.constructor import SafeConstructor

def construct_float_or_string(self, node):
    # 获取节点的原始字符串值
    raw_value = node.value
    # 判断是否是带末尾0的小数格式(如0.20、1.30这类)
    if '.' in raw_value:
        integer_part, decimal_part = raw_value.split('.', 1)
        if decimal_part.endswith('0') and len(decimal_part) > 1:
            return raw_value
    # 不符合规则的按正常浮点数解析
    return super().construct_float(self, node)

# 替换SafeConstructor的浮点数构造方法
SafeConstructor.constructors['tag:yaml.org,2002:float'] = construct_float_or_string

# 加载并解析YAML文件
with open("example.yaml", "r") as stream:
    try:
        result = yaml.safe_load(stream)
        print(result)
    except yaml.YAMLError as exc:
        print(exc)

运行这段代码后,输出将符合预期:{'version': '0.20'}。

如果需要更精准地只处理version字段,也可以尝试在解析完成后对特定键进行格式还原,但这种方法依赖浮点数的字符串格式化,可能存在精度问题,因此更推荐上述在解析阶段处理的方案。


内容的提问来源于stack exchange,提问作者sravya amiri

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 15:35:38