用随机数替换 YAML 文件中的数字

Replace numbers in YAML file with random numbers

我有一个包含很多数字的文件。我希望每个数字都将替换为一个随机数。以便 Python 脚本更改 YAML 文件。如何在 Python 中编码?

!h 1: {X: '-950,00000', Y: '1500,00000', Z: '150,00000'}
!h 2: {X: '-950,00000', Y: '1500,00000', Z: '150,00000'}
!h 3: {X: '-950,00000', Y: '1500,00000', Z: '150,00000'}
!h 4: {X: '-950,00000', Y: '1500,00000', Z: '150,00000'}
!h 5: {X: '-950,00000', Y: '1500,00000', Z: '150,00000'}
!h 6: {X: '-950,00000', Y: '1500,00000', Z: '150,00000'}

你可以用 ruamel.yaml 做到这一点。有多种生成随机数的方法,因为 你需要它们作为标量字符串,用逗号作为小数点分隔符,我建议使用 random.randrange 并将结果作为字符串进行操作:

import sys
from random import randrange
from pathlib import Path
import ruamel.yaml

in_file = Path('input.yaml')
out_file = Path('output.yaml')

def randfloatstr():
    # this gives you max 4 digits before the comma and 5 digits after
    x = str(randrange(0, 1000000000))
    return x[:-5] + ',' + x[-5:]
    
yaml = ruamel.yaml.YAML()
data = yaml.load(in_file)
for v in data.values():
    for k in v:
        v[k] = randfloatstr()

yaml.dump(data, out_file)
sys.stdout.write(out_file.read_text())

给出:

!h 1: {X: '2767,85747', Y: '8281,59187', Z: '2729,91875'}
!h 2: {X: '324,84623', Y: '6669,00402', Z: '6183,89608'}
!h 3: {X: '5349,15868', Y: '7987,69554', Z: '243,05155'}
!h 4: {X: '6738,35201', Y: '2497,61750', Z: '2933,25689'}
!h 5: {X: '6013,68067', Y: '5265,31446', Z: '9229,21356'}
!h 6: {X: '4656,47702', Y: '4710,97938', Z: '5264,45726'}

ruamel.yaml 将保留标签 (!h),但不能为较小的数字对齐列。