Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
60 views
in Technique[技术] by (71.8m points)

python - Prettier floats using yaml

Whenever I use yaml dump to dump floats, they start to look ugly.

Input:

a.yaml

a: 0.000000015

When I read it in and then dump it to file again, it will look like:

dumped.yaml

a: 1.5e-08

Note that there's no fixed size I can go for, i.e. maybe someone wants to put a lot of zeros (and I am not "afraid" of e.g. a small fraction with 20 leading zeros)

Also, if you choose a fixed size, then it might look like the following (which I am trying to avoid as well)

a: 0.0000000150000
question from:https://stackoverflow.com/questions/65602544/prettier-floats-using-yaml

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I haven't been able to find, in the format specification mini-language documentation, a way to format numbers the way you want them.

I propose a simple hack: to replace, in the output of PyYAML, all numbers in scientific notation with their fixed-point equivalent, like this:

import re
import yaml

# only accepts Python's/PyYAML's default scientific format, on purpose:
E_REGEX = re.compile(r'(|-)([1-9])(?:.(d+))?e([+-])(d+)')

def e_to_f(match):
    sf, f0, f1, se, e = match.groups()
    if f1 is None: f1 = ''
    f = f0 + f1
    n = int(e)
    if se == '-':
        z = n - 1  # i.e., n - len(f0)
        if z < 0:
            return sf + f[:-z] + '.' + f[-z:]
        else:
            return sf + '0.' + '0' * z + f
    else:
        z = n - len(f1)
        if z < 0:
            return sf + f[:z] + '.' + f[z:]
        else:
            return sf + f + '0' * z + '.0'

e_dict = {
    'example': 1.5e-15,
    'another': -3.14e+16
}
e_txt = yaml.dump(e_dict, sort_keys=False)
f_txt = E_REGEX.sub(e_to_f, e_txt)
print(e_txt)
print(f_txt)

# output:
#
# example: 1.5e-15
# another: -3.14e+16
#
# example: 0.0000000000000015
# another: -31400000000000000.0


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...