【问题标题】:Convert data in String format to List - python将字符串格式的数据转换为列表 - python
【发布时间】:2015-01-10 09:56:19
【问题描述】:

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

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

【问题讨论】:

    标签: python regex list


    【解决方案1】:

    在每一行拨打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']]
    

    【讨论】:

    • 感谢您的帮助。我想将一个数据条目作为一个列表条目。但是,这实际上是一个更好的主意,但是我需要列表中的多个数据条目,我应该循环并将列表条目添加到数组中吗?
    • 您可以在帖子中添加您想要的输出示例吗?
    • 非常感谢!我爱你!
    【解决方案2】:

    假设您的文件名为test.data

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-07-18
      • 2021-11-09
      • 1970-01-01
      • 1970-01-01
      • 2020-12-15
      • 1970-01-01
      • 2022-08-17
      • 1970-01-01
      相关资源
      最近更新 更多