Python中灵活的数字字符串解析 [英] Flexible numeric string parsing in Python

查看:220
本文介绍了Python中灵活的数字字符串解析的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

除了内置的float()函数所支持的功能之外,是否还有任何Python库可以帮助解析和验证数字字符串?例如,除了简单的数字(1234.56)和科学计数法(3.2e15),我还希望能够解析以下格式:

Are there any Python libraries that help parse and validate numeric strings beyond what is supported by the built-in float() function? For example, in addition to simple numbers (1234.56) and scientific notation (3.2e15), I would like to be able to parse formats like:

  • 带逗号的数字:2,147,483,647
  • 大名:55亿
  • 分数:1/4

我做了一些搜索,却找不到任何东西,尽管如果这样的库还不存在,我会感到惊讶.

I did a bit of searching and could not find anything, though I would be surprised if such a library did not already exist.

推荐答案

如果要转换本地化"数字,例如美国的"2,147,483,647"形式,则可以使用

If you want to convert "localized" numbers such as the American "2,147,483,647" form, you can use the atof() function from the locale module. Example:

import locale
locale.setlocale(locale.LC_NUMERIC, 'en_US')
print locale.atof('1,234,456.23')  # Prints 1234456.23

对于分数,Python现在可以直接处理它们(从2.6版开始);它们甚至可以从字符串构建:

As for fractions, Python now handles them directly (since version 2.6); they can even be built from a string:

from fractions import Fraction
x = Fraction('1/4')
print float(x)  # 0.25

因此,仅在以上两个标准模块的帮助下,您才能解析以前三种方式中的任何一种编写的数字:

Thus, you can parse a number written in any of the first 3 ways you mention, only with the help of the above two standard modules:

try:
    num = float(num_str)
except ValueError:
    try:
        num = locale.atof(num_str)
    except ValueError:
        try:
            num = float(Fraction(num_str))
        except ValueError:
            raise Exception("Cannot parse '%s'" % num_str)  # Or handle '42 billion' here
# 'num' has the numerical value of 'num_str', here.        

这篇关于Python中灵活的数字字符串解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆