2016-08-03 16 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.4 = 14/10を読み取ることになるので、14 次()間、小数点以下1桁を有します。 23.30の場合、0.14 = 14/100となります。

可能であれば教えてください。みんなありがとう。このようなものについてはどのように

+1

正規表現では数値を数えたり分けたりすることはできません。正規表現を使用して数字を照合し、小数点以下の桁数を決定するPython関数を書くことができます。 –

+0

@ Tim:フィードバックありがとうございます。正規表現や関数の部分についての提案はありますか? – 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

@ Excellent!ありがとうございました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

関連する問題