首页 > 解决方案 > 使用python转换空格分隔的文本文件?

问题描述

我正在尝试将此空格分隔的文本文件转换为列和行(我想最终将其转换为 JSON)。我的脚本可能无法分隔列,主要是因为我正在寻找空格。我无法更改输入的格式(输入的文本文件)

我的文件格式有问题,这是一个非常简单的例子

col1 col2                 col3 text                      col4

1403 bash                 2014-07-28 22:32:53 UTC+0000   sudo bash
1464 bash                 2014-07-28 22:32:28 UTC+0000   sudo root

当我解析文件时,我得到了破折号下方的数据:

['1403', 'bash', '2014-07-28', '22:32:53', 'UTC+0000', 'sudo', 'bash']

我希望它看起来像这样:

['1403', 'bash', '2014-07-28 22:32:53 UTC+0000', 'sudo bash']

这是一个非常基本的例子。但基本上我将标题映射到破折号下方的数据。让我知道您是否可以提供任何帮助。

注意:输出不必完全如图所示,我只是希望能够分离 cols 数据。

到目前为止,这是我在代码中拥有的内容,它将标头分隔为各个列:

colNames = testFile.readline()
#tempList = re.split('(\s )', colNames)
headerList = []
for i in tempList:
    j = i.replace(' ','')
    if j != '':
        headerList.append(j)

然后我有一个循环来根据数据的位置遍历数据(这是我认为我需要找到一种更好地分离数据的方法):

   for line in testFile.readlines():
        if rowCounter > 0:
            row = line.split()
            print row
            for i in range(len(headerList)):
                colNameDic.update({headerList[i]:row[i]})
            rowDic = dict(colNameDic)
            fileList.append(rowDic)
            rowDic = {}
        rowCounter +=1

标签: pythonjsontexttype-conversionwhitespace

解决方案


如果标题行在列名中没有多余的空格,则可以使用内置函数拆分数据行slice(请注意,我在标题行中添加了一个下划线以规范列名)

In [20]: h = 'col1 col2                 col3_text                      col4\n'
In [21]: r = '1403 bash                 2014-07-28 22:32:53 UTC+0000   sudo bash\n'
In [22]: fields = h.split()
    ...: ifields = [h.index(f) for f in fields]+[None]
In [23]: slices = [slice(i,j) for i, j in zip(ifields, ifields[1:])]
In [24]: tokens = [r[s] for s in slices]
In [25]: tokens
Out[25]: 
['1403 ',
 'bash                 ',
 '2014-07-28 22:32:53 UTC+0000   ',
 'sudo bash\n']
In [26]: 

PS你可能想要rstrip个别项目,[r[s].rstrip() for s in slices]


附录

如果可以在有效列名和垃圾之间找到判别式,则可以放宽无多余空格的要求...重新使用您的特定数据格式(无下划线...)

In [35]: h = 'col1 col2                 col3 text                      col4\n'
In [36]: r = '1403 bash                 2014-07-28 22:32:53 UTC+0000   sudo bash\n'
In [37]: fields = [f for f in h.split() if f[:3]=='col']
In [38]: ifields = [h.index(f) for f in fields]+[None]
In [39]: slices = [slice(i,j) for i, j in zip(ifields, ifields[1:])]
In [40]: tokens = [r[s].rstrip() for s in slices]
In [41]: tokens
Out[41]: ['1403', 'bash', '2014-07-28 22:32:53 UTC+0000', 'sudo bash']
In [42]: 

推荐阅读