将字符串格式的数据转换为列表格式

2024-09-27 21:26:01 发布

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

我有一个数据结构如下的文本文件:

01/May/1998:15:28:53    test123 0   383L    281L    399
01/May/1998:14:23:28    doe821  62C 621L    379
01/May/1998:22:10:11    testABC 0   635R    407R    671R    671N    407N    407Q    407L    496L    569

每个数据都以如下格式的日期和时间开始:01/May/1998:15:28:53。你知道吗

我开始阅读文本文件,但现在我想把它转换成一个列表。我该怎么做? 我需要正则表达式吗?你知道吗

任何帮助都将不胜感激。你知道吗

编辑: 我想要这个输出:

    [
      ['01/May/1998:15:28:53', 'test123', '0', '383L', '281L', '399'],
      ['01/May/1998:14:23:28', 'doe821', '62C', '621L', '379'],
      ['01/May/1998:22:10:11', 'testABC', '0', '635R', '407R', '671R', '671N', '407N', '407Q', '407L', '496L', '569']
    ]

Tags: 数据编辑数据结构列表格式时间may文本文件
2条回答

假设您的文件名为test.data

>>> with open('test.data') as f:
>>>     [x for x in [y.split() for y in f.read().split('\n')]]

在每一行上调用str.split()将为您提供:

 ['01/May/1998:15:28:53', 'test123', '0', '383L', '281L', '399']

例如:

with open('textfile') as f:
    for line in f:
        print line.split()

['01/May/1998:15:28:53', 'test123', '0', '383L', '281L', '399']
['01/May/1998:14:23:28', 'doe821', '62C', '621L', '379']
['01/May/1998:22:10:11', 'testABC', '0', '635R', '407R', '671R', '671N', '407N', '407Q', '407L', '496L', '569']

将每一行作为一个列表项:

with open('textfile') as f:
    print f.readlines() # note the newline chars(\n) that may need slicing off

['01/May/1998:15:28:53    test123 0   383L    281L    399\n', '01/May/1998:14:23:28    doe821  62C 621L    379\n', '01/May/1998:22:10:11    testABC 0   635R    407R    671R    671N    407N    407Q    407L    496L    569\n']

要将每行拆分并放在一个大列表中:

with open('textfile') as f:
    print [line.split() for line in f]

[['01/May/1998:15:28:53', 'test123', '0', '383L', '281L', '399'], ['01/May/1998:14:23:28', 'doe821', '62C', '621L', '379'], ['01/May/1998:22:10:11', 'testABC', '0', '635R', '407R', '671R', '671N', '407N', '407Q', '407L', '496L', '569']]

相关问题 更多 >

    热门问题