2016-08-03 55 views
1

我正在研究Python 2.7中的一个复杂正则表达式,以便从文件中读取以下格式。行(读作一个字符串)看起来像这样:带有括号和小数点的Python正则表达式

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。

请让我知道这是否可能。多谢你们。

+1

正则表达式不能计数也不能分开数字,它们与文本匹配。您可以使用正则表达式来匹配您的数字,然后编写一个Python函数来确定小数点后的位数。 –

+0

@蒂姆:感谢您的反馈。你有正则表达式或函数部分的建议吗? – remi

回答

2

你还可去:

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

+0

@优秀!非常感谢Jan。 – remi

+0

@remi:你很受欢迎。 – Jan

3

怎么是这样的:

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)]

+0

@ Tim:作品也很完美。对于进一步处理,我只对列表格式略有偏好。 – remi