16 python
Python喜欢提出异常,这通常很棒.但我正面临着一些我迫切希望使用C的atoi/atof语义转换为整数的字符串 - 例如atoi的"3 of 12","3/12","3/12",都应该变为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
Run Code Online (Sandbox Code Playgroud)
Ale*_*lli 38
如果你非常热衷于获得c的功能atoi,为什么不直接使用呢?例如,在我的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
Run Code Online (Sandbox Code Playgroud)
在Linux,Windows等中,相同的代码应该可以工作,除非你检查一下你会看到一个不同的路径whereislib(只有真正的,非常特殊的安装才能使这个代码无法找到C运行时库).
如果你热衷于避免使用直接的C库,我猜你可以获取相关的前缀,例如使用RE等r'\s*([+-]?\d+)',并尝试int使用它.
我认为迭代版本比递归版本更好
# 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")
Run Code Online (Sandbox Code Playgroud)
也许使用快速正则表达式只抓取可以被认为是数字的字符串的第一部分?就像是...
-?[0-9]+(?:\.[0-9]+)?
Run Code Online (Sandbox Code Playgroud)
对于浮子和整体而言,
-?[0-9]+
Run Code Online (Sandbox Code Playgroud)
使用正则表达式执行此操作非常简单:
>>> 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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
26357 次 |
| 最近记录: |