Python 带括号和小数位的正则表达式

Python regex with parenthesis and decimal place

我正在研究 Python 2.7 中的复杂正则表达式以从文件中读取以下格式。这些行(读作字符串)如下所示:

 line = 23.3(14) 600(3)   760.35(10)

最终所需的输出将是一个列表(或其他),将行解析为:

list = 23.3 1.4 600 3 760.35 0.10 ; list[0]=23.3, list[1]=1.4 ....

正则表达式应该读取 () 之间的数字,但也计算它前面的数字(最左边)的位数,以正确解释 () 之间的值。

例子: 23.3小数点后有1位,所以14在下一个()之间 会读作 1.4 = 14/10。如果 23.30 那么 0.14=14/100。

如果可行,请告诉我。谢谢你们。

这样的事情怎么样:

import re
s = "23.3(14) 600(3)   760.35(10)"

def digits(s):                # return the number of digits after the decimal point
    pos = s.find(".")
    if pos == -1:             # no decimal point
        return 0
    else:
        return len(s)-pos-1   # remember that indices are counted from 0

matches = re.findall(r"([\d.]+)\((\d+)\)", s) # find all number pairs
l = []
for match in matches:
    d = digits(match[0])
    if d:                     # More than 0 digits?
        l.append((float(match[0]), float(match[1]) / 10**d))
    else:                     # or just integers?
        l.append((int(match[0]), int(match[1])))

结果l[(23.3, 1.4), (600, 3), (760.35, 0.1)]

你也可以选择:

import re

line = "23.3(14) 600(3)   760.35(10)"

# split the items
rx = re.compile(r"\d[\d().]+")
digits = rx.findall(line)

# determine the length
def countandsplit(x):
    ''' Finds the length and returns new values'''
    a = x.find('(')
    b = x.find('.')
    if a != -1 and b != -1:
        length = a-b-1
    else:
        length = 0

    parts = list(filter(None, re.split(r'[()]', x)))
    number1 = float(parts[0])
    number2 = round(float(parts[1]) * 10 ** -length, length)
    return [number1, number2]

# loop over the digits
result = [x for d in digits for x in countandsplit(d)]
print(result)
# [23.3, 1.4, 600.0, 3.0, 760.35, 0.1]


参见 a demo on ideone.com