2012-12-05 36 views
-1

我有一种形式的数据,类别和值位于由“;”分隔的同一行中。如下所示:如何使用动态列数重新格式化数据

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

在每一行的数据是这样的,可能有不同数量的类别。所以,第一行可能有category1到category5,而第二行可能有category1到category10。类别总是按顺序排列。

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

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

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

任何想法如何做到这一点。任何Linux bash脚本都可以,但python比我更可取。

+0

类别或值可以包含括号? – unutbu

+0

@unutbu值可以有任何字符。但类别周围有大括号;值对也如图所示。 – sfactor

+0

如果'value'可以包含任何字符,那么应该使用什么规则来确定“{{category1; value},{category2; value}}”没有被分析为具有一个类别“category1”,值为value },{category2; value'? – unutbu

回答

0

可能有办法做到这一点的数字,但用一个可行的办法是

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

,但其他的变形小的变化正则表达式

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

给出评论,这听起来像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 
相关问题