相当于atoi的Python/

2024-10-06 16:26:48 发布

您现在位置:Python中文网/ 问答频道 /正文

Python喜欢引发异常,这通常很好。但我面对的是一些我非常想用C的atoi/atof语义转换成整数的字符串——例如“3 of 12”、“3/12”、“3/12”的atoi都应该变成3;atof(“3.14秒”)应该变成3.14;atoi(“99分”)应该变成-99。当然,Python有atoi和atof函数,它们的行为与atoi和atof完全不同,与Python自己的int和float构造函数完全相同。

到目前为止,我拥有的最好的版本,非常难看,很难扩展到各种可用的浮点格式:

value = 1
s = str(s).strip()
if s.startswith("-"):
    value = -1
    s = s[1:]
elif s.startswith("+"):
    s = s[1:]
try:
    mul = int("".join(itertools.takewhile(str.isdigit, s)))
except (TypeError, ValueError, AttributeError):
    mul = 0
return mul * value

Tags: of函数字符串版本value语义整数float
3条回答

我认为迭代版本比递归版本好

# Iterative
def atof(s):
    s,_,_=s.partition(' ') # eg. this helps by trimming off at the first space
    while s:
        try:
            return float(s)
        except:
            s=s[:-1]
    return 0.0

# Recursive
def atof(s):
    try:
        return float(s)
    except:
        if not s:
            return 0.0
        return atof(s[:-1])


print atof("3 of 12")
print atof("3/12")
print atof("3 / 12")
print atof("3.14 seconds")
print atof("314e-2 seconds")
print atof("-99 score")
print atof("hello world")

对正则表达式执行此操作非常简单:

>>> import re
>>> p = re.compile(r'[^\d-]*(-?[\d]+(\.[\d]*)?([eE][+-]?[\d]+)?)')
>>> def test(seq):
        for s in seq:
            m = p.match(s)
            if m:
                result = m.groups()[0]
                if "." in result or "e" in result or "E" in result:
                    print "{0} -> {1}".format(s, float(result))
                else:
                    print '"{0}" -> {1}'.format(s, int(result))
            else:
                print s, "no match"

>>> test(s)
"1 0" -> 1
"3 of 12" -> 3
"3 1/2" -> 3
"3/12" -> 3
3.15 seconds -> 3.15
3.0E+102 -> 3e+102
"what about 2?" -> 2
"what about -2?" -> -2
2.10a -> 2.1

如果您非常希望获得c的atoi功能,为什么不直接使用它呢?E、 g.在我的Mac上

>>> import ctypes, ctypes.util
>>> whereislib = ctypes.util.find_library('c')
>>> whereislib
'/usr/lib/libc.dylib'
>>> clib = ctypes.cdll.LoadLibrary(whereislib)
>>> clib.atoi('-99foobar')
-99

在Linux、Windows等操作系统中,相同的代码应该可以工作,但是如果您检查whereislib,您将看到不同的路径(只有在真正的、非常特殊的安装中,如果此代码找不到C运行时库)。

如果你想避免直接使用C库,我想你可以获取相关的前缀,例如使用re,比如r'\s*([+-]?\d+)',然后尝试int

相关问题 更多 >