在python中解析通用数据文件

时间:2014-07-04 15:44:04

标签: python parsing

我的数据文件非常简单,格式为title : data。 例如(真实文件相同但数据更多):

Images : 50
Total cells : 532
Viable cells : 512
Nonviable cells : 20

现在要解析这个,我想要的每个数据都有以下代码:

if data[1][:12] == "Total Cells :":
    result.append(data[1][13:-1])

这感觉就像一个非常肮脏的解决方案。什么是解决这个问题的更干净的方法?

3 个答案:

答案 0 :(得分:3)

您可以简单地在' : '上分割线:

key, value = data[1].split(' : ', 1)

现在,您将该行的两个元素分成两个变量。你可能想要删除这些无关的空白:

key, value = map(str.strip, data[1].split(':', 1))

演示:

>>> map(str.strip, 'Images : 50'.split(':'))
['Images', '50']
>>> map(str.strip, 'Total cells : 532'.split(':'))
['Total cells', '532']

答案 1 :(得分:3)

如果您希望将此数据文件放在一个漂亮的字典中,您可以执行以下操作:

d = {}
for line in data:
    key, value = line.split(':')
    d[key] = value

打印出d将返回:

{'Images': 50, 'Total cells': 532, 'Viable cells': 512, 'Nonviable cells': 20}

这假设没有你的"键"或者"价值观"其中有:

然后您可以访问任何元素(即" Total Cells"),如下所示:

print d['Total cells']

答案 2 :(得分:0)

您可以使用str.split()但是您可以使用str.partition(), 这是帮助文本:

partition

partition(...)
    S.partition(sep) -> (head, sep, tail)

    Search for the separator sep in S, and return the part before it,
    the separator itself, and the part after it.  If the separator is not
    found, return S and two empty strings.

split

split(...)
    S.split([sep [,maxsplit]]) -> list of strings

    Return a list of the words in the string S, using sep as the
    delimiter string.  If maxsplit is given, at most maxsplit
    splits are done. If sep is not specified or is None, any
    whitespace string is a separator and empty strings are removed
    from the result.

我建议使用简单的界面:

>>> line = "Images : 50"
>>> key, sep, value = line.partition(" : ")
>>> key, sep, value
('Images', ' : ', '50')

你可以使用一些东西:

result = {}
for line in data:
    # this assumes : is always surrounded by spaces.
    key, sep, value = line.partition(" : ")
    # seems like value is a number...
    result[key] = int(value)