私はPythonの初心者ですが、現在はカスタム出力形式の文字列を解析するために使用しようとしています。実際のフォーマットには、floatの名前付きリストとfloatのタプルのリストが含まれています。私は関数を書いたが、それは過度に見える。どのようにしてより適切な方法でPythonを行うことができますか?Pythonを使用して特定の形式の文字列からデータを抽出する
import re
def extract_line(line):
line = line.lstrip('@ ')
measurement_list = list(filter(None, re.split(r'\s*;\s*', line)))
measurement = {}
for elem in measurement_list:
elem_list = list(filter(None, re.split(r'\s*=\s*', elem)))
name = elem_list[0]
if name == 'points':
points = list(filter(None, re.split(r'\s*\(\s*|\s*\)\s*',elem_list[1].strip(' {}'))))
for point in points:
p = re.match(r'\s*(\d+(?:\.\d+)?)\s*,\s*(\d+(?:\.\d+)?)\s*', point).groups()
if 'points' not in measurement.keys():
measurement['points'] = []
measurement['points'].append(tuple(map(float,p)))
else:
values = list(filter(None, elem_list[1].strip(' {}').split(' ')))
for value in values:
if name not in measurement.keys():
measurement[name] = []
measurement[name].append(float(value))
return measurement
to_parse = '@10 points = { (2.96296 , 0.822213) (3.7037 , 0.902167) } ; L = { 5.20086 } ; P = { 3.14815 3.51852 } ;'
print(extract_line(to_parse))
いいえ、そうではありません。 {'points':[(2.96296,0.822213)、(3.7037,0.902167)]、 'L':[5.20086]、 'P':[3.14815,3.51852]のようなものが必要です。 – allaspaniel