【问题标题】:Extracting data from string with specific format using Python使用 Python 从具有特定格式的字符串中提取数据
【发布时间】:2016-03-31 18:57:07
【问题描述】:

我是 Python 新手,目前我正在尝试使用它来解析一些自定义输出格式化字符串。事实上,格式包含命名的浮点列表和浮点元组列表。我写了一个函数,但它看起来过分了。如何以更适合 Python 的方式完成?

import re

def extract_line(line):
    line = line.lstrip('0123456789@ ')
    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))

【问题讨论】:

    标签: python regex parsing format


    【解决方案1】:

    您可以使用 re.findall 来做到这一点:

    import re
    to_parse = '@10 points = { ( 2.96296 , 0.822213 ) ( 3.7037 , 0.902167 ) } ; L = { 5.20086 } ; P = { 3.14815 3.51852 } ;'
    
    m_list = re.findall(r'(\w+)\s*=\s*{([^}]*)}', to_parse)
    measurements = {}
    for k,v in m_list:
        if k == 'points':
            elts = re.findall(r'([0-9.]+)\s*,\s*([0-9.]+)', v)
            measurements[k] = [tuple(map(float, elt)) for elt in elts]
        else:
            measurements[k] = [float(x) for x in v.split()]
    
    print(measurements)
    

    随意将其放入函数中并检查键是否不存在。

    【讨论】:

      【解决方案2】:

      这个:

      import re
      a=re.findall(r' ([\d\.eE-]*) ',to_parse)
      map(float, a)
      >> [2.96296, 0.822213, 3.7037, 0.902167, 5.20086, 3.14815]
      

      会给你你的号码列表,是你要找的吗?

      【讨论】:

      • 不,不是。我需要这样的东西:{'points': [(2.96296, 0.822213), (3.7037, 0.902167)], 'L': [5.20086], 'P': [3.14815, 3.51852]}
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-03-13
      • 2017-12-31
      • 2017-12-21
      • 1970-01-01
      • 2021-10-20
      • 1970-01-01
      • 2020-07-24
      相关资源
      最近更新 更多