如何使用动态列数重新格式化数据

2024-04-18 20:53:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这样一种形式的数据:类别和值在同一行中,用“;”分隔,如下所示:

{{category1;value}, {category2;value}, {category3;value} ....}}

每一行的数据都可能有不同数量的类别。因此,第一行可能有类别1到类别5,而第二行可能有类别1到类别10。不过,分类总是按顺序排列的。你知道吗

我需要解析数据并创建一个新文件,以便在列标题中有类别的名称,在相应的行中有值。你知道吗

category1        category2        category3       category4    ....
 value             value             value          value

但由于我不能说可能有多少个类别,我需要添加每个新列。所以,解析第一行我就知道有5列(cat1到cat5),但是对于第二行,我必须添加cat6到cat10的列,以此类推。你知道吗

你知道怎么做吗。任何Linux bash脚本都可以,但python对我来说更可取。你知道吗


Tags: 文件数据名称标题数量value分类类别
2条回答

给出注释后,听起来category可以包含分号以外的任何字符,value可以包含右大括号以外的任何字符,因为这些字符会过早终止categoryvalue。你知道吗

在这种情况下,可以使用正则表达式来匹配模式。你知道吗

import re

def report(text):
    # Remove surrounding whitespace and braces
    text = text.strip()[1:-1]   
    pairs = re.findall(
        r'''\{      # literal open brace
            (.+?)   # one-or-more characters, stop at the first
            ;       # literal semicolon
            (.+?)   # one-or-more characters, stop at the first
            \}      # literal closed brace
            ''', text, re.VERBOSE)
    categories, values = zip(*pairs)
    widths = [max(map(len, item)) for item in pairs]
    fmt = '{x:^{w}}'
    for row in (categories, values):
        print('    '.join([fmt.format(x = x, w = w) for x, w in zip(row, widths)]))

tests = """\
{{category1;value}, {category2;value}}
{{category1;value}, {category2;value}, {category3;value}}
{{categ{,ory1;val;ue}, {category2;val{ue}, {category3;value}}
""".splitlines()

for test in tests:
    report(test)

收益率

category1    category2
  value        value  
category1    category2    category3
  value        value        value  
categ{,ory1    category2    category3
  val;ue        val{ue        value  

可能有很多方法可以做到这一点,但一个可能的方法是

>>> rows = data.translate(None,"{}").replace(";",",").split(",")
>>> rows[::2]
['category1', ' category2', ' category3']
>>> rows[1::2]
['value', 'value', 'value']

和上面的小变化

>>> rows = dict(e.split(';') for e in data.translate(None,"{}").split(","))
>>> rows.keys()
['category1', ' category2', ' category3']
>>> rows.values()
['value', 'value', 'value']

还有另一个使用regex的变体

>>> rows = re.split("[\{\},; ]+",data)[1:-1]
>>> rows[::2]
['category1', 'category2', 'category3']
>>> rows[1::2]
['value', 'value', 'value']

相关问题 更多 >