如何在Python中将浮点数格式化为最大固定宽度

6
我正在为一个有根于60年代的程序编写输入文件,它从文本文件的固定宽度数据字段中读取数据。格式如下:
  • 字段宽度为8个字符
  • 浮点数必须包含一个'.' 或者写成指数形式,例如'1.23e8'
到目前为止,我得到的最接近的结果是:
print "{0:8.3g}".format(number)

下面是翻译的结果:

使用 1234567 得到 '1234567.',使用 1234 得到 ' 1234.'

但我想要更改:

  • 1234567.,使用 1234567(即在需要指数格式之前不转换为指数格式),
  • 1234.,使用 1234(即以点结尾,这样它不会被解释为整数),
  • 1.235e+7,使用 12345678(即为指数使用一个数字),
  • -1.23e+7,使用 -1234567(即不违反负数的8位数最大值)。

由于这在 Fortran 中很容易实现,并且在与旧代码交互时可能经常出现问题,因此我认为一定有一种简单的方法可以解决这个问题?

4个回答

3
我将简单地采用@Harvey251的回答,将其分为测试部分和我们在生产中需要的部分。
使用方法如下:
Original Answer翻译成"最初的回答"
# save the code at the end as formatfloat.py and then
import formatfloat

# do this first
width = 8
ff8 = formatfloat.FormatFloat(width)

# now use ff8 whenever you need
print(ff8(12345678901234))

这里是解决方案。将代码保存为formatfloat.py并导入以使用FlotFormat类。正如我在下面所说的那样,计算的循环部分最好移动到FormatFlot类的init部分。

原始答案:最初的回答

import unittest

class FormatFloat:
    def __init__(self, width = 8):
        self.width = width
        self.maxnum = int('9'*(width - 1))  # 9999999
        self.minnum = -int('9'*(width - 2)) # -999999

    def __call__(self, x):

        # for small numbers
        # if -999,999 < given < 9,999,999:
        if x > self.minnum and x < self.maxnum:

            # o = f'{x:7}'
            o = f'{x:{self.width - 1}}'

            # converting int to float without adding zero
            if '.' not in o:
                o += '.'

            # float longer than 8 will need rounding to fit width
            elif len(o) > self.width:
                # output = str(round(x, 7 - str(x).index(".")))
                o = str(round(x, self.width-1 - str(x).index('.')))

        else:

            # for exponents
            # added a loop for super large numbers or negative as "-" is another char
            # Added max(max_char, 5) to account for max length of less 
            #     than 5, was having too much fun
            # TODO can i come up with a threshold value for these up front, 
            #     so that i dont have to do this calc for every value??
            for n in range(max(self.width, 5) - 5, 0, -1):
                fill = f'.{n}e'
                o = f'{x:{fill}}'.replace('+0', '+')

                # if all good stop looping
                if len(o) == self.width:
                    break
            else:
                raise ValueError(f"Number is too large to fit in {self.width} characters", x)
        return o


class TestFormatFloat(unittest.TestCase):
    def test_all(self):
        test = ( 
            ("1234567.", 1234567), 
            ("-123456.", -123456), 
            ("1.23e+13", 12345678901234), 
            ("123.4567", 123.4567), 
            ("123.4568", 123.45678), 
            ("1.234568", 1.2345678), 
            ("0.123457", 0.12345678), 
            ("   1234.", 1234), 
            ("1.235e+7", 12345678), 
            ("-1.23e+6", -1234567),
            )

        width = 8
        ff8 = FormatFloat(width)

        for expected, given in test:
            output = ff8(given)
            self.assertEqual(len(output), width, msg=output)
            self.assertEqual(output, expected, msg=given)

if __name__ == '__main__':
    unittest.main()

3

我对yosukesabai的贡献进行了微小的修改,以解决舍入导致字符串宽度为7个字符而不是8个字符的罕见情况!

class FormatFloat:
def __init__(self, width = 8):
    self.width = width
    self.maxnum = int('9'*(width - 1))  # 9999999
    self.minnum = -int('9'*(width - 2)) # -999999

def __call__(self, x):

    # for small numbers
    # if -999,999 < given < 9,999,999:
    if x > self.minnum and x < self.maxnum:

        # o = f'{x:7}'
        o = f'{x:{self.width - 1}}'

        # converting int to float without adding zero
        if '.' not in o:
            o += '.'

        # float longer than 8 will need rounding to fit width
        elif len(o) > self.width:
            # output = str(round(x, 7 - str(x).index(".")))
            o = str(round(x, self.width - 1 - str(x).index('.')))
            if len(o) < self.width:
                o+=(self.width-len(o))*'0'

    else:

        # for exponents
        # added a loop for super large numbers or negative as "-" is another char
        # Added max(max_char, 5) to account for max length of less 
        #     than 5, was having too much fun
        # TODO can i come up with a threshold value for these up front, 
        #     so that i dont have to do this calc for every value??
        for n in range(max(self.width, 5) - 5, 0, -1):
            fill = f'.{n}e'
            o = f'{x:{fill}}'.replace('+0', '+')

            # if all good stop looping
            if len(o) == self.width:
                break
        else:
            raise ValueError(f"Number is too large to fit in {self.width} characters", x)
    return o

1
你显然已经非常接近解决方案,但我认为你的最终解决方案将涉及编写自定义格式化程序。例如,我不认为 迷你格式语言可以像您想要的那样控制指数的宽度。
(顺便说一下,在您的第一个示例中,“e”后面没有“+”,但在其他示例中有。明确您想要哪个可能有助于其他回答者。)
如果我要编写此格式化函数,首先要做的是编写全面的测试集。doctestunittest都可以使用。
然后您可以修改您的格式化函数,直到所有这些测试都通过。

1
你可以做类似的事情,虽然有点晚了,我花了太长时间才找到类似的解决方法。
import unittest


class TestStringMethods(unittest.TestCase):

    def test_all(self):
        test = (
            ("1234567.", 1234567),
            ("-123456.", -123456),
            ("1.23e+13", 12345678901234),
            ("123.4567", 123.4567),
            ("123.4568", 123.45678),
            ("1.234568", 1.2345678),
            ("0.123457", 0.12345678),
            ("   1234.", 1234),
            ("1.235e+7", 12345678),
            ("-1.23e+6", -1234567),
        )

        max_char = 8
        max_number = int("9" * (max_char - 1))  # 9,999,999
        min_number = -int("9" * (max_char - 2))  # -999,999
        for expected, given in test:
            # for small numbers
            # if -999,999 < given < 9,999,999:
            if min_number < given < max_number:

                # output = f"{given:7}"
                output = f"{given:{max_char - 1}}"

                # converting ints to floats without adding zero
                if '.' not in output:
                    output += '.'

                # floats longer than 8 will need rounding to fit max length
                elif len(output) > max_char:
                    # output = str(round(given, 7 - str(given).index(".")))
                    output = str(round(given, max_char - 1 - str(given).index(".")))

            else:
                # for exponents
                # added a loop for super large numbers or negative as "-" is another char
                # Added max(max_char, 5) to account for max length of less than 5, was having too much fun
                for n in range(max(max_char, 5) - 5, 0, -1):
                    fill = f".{n}e"
                    output = f"{given:{fill}}".replace('+0', '+')
                    # if all good stop looping
                    if len(output) == max_char:
                        break
                else:
                    raise ValueError(f"Number is too large to fit in {max_char} characters", given)

            self.assertEqual(len(output), max_char, msg=output)
            self.assertEqual(output, expected, msg=given)


if __name__ == '__main__':
    unittest.main()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接