用python解析通用数据文件

2024-09-24 22:25:30 发布

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

我有一个非常简单的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])

不过,这似乎是一个非常肮脏的解决方案。解决这个问题的更干净的方法是什么?你知道吗


Tags: 文件数据代码dataiftitle数据文件格式
3条回答

你可以使用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)

只需在' : '上拆分行:

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

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

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

打印d将返回:

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

这假设您的“键”或“值”中没有:。你知道吗

然后可以访问任何元素(即“总单元格”),如下所示:

print d['Total cells']

相关问题 更多 >