【问题标题】:How do I get a value from a specific column and row from CLI output in Python 3如何从 Python 3 中的 CLI 输出的特定列和行中获取值
【发布时间】:2020-09-25 06:55:42
【问题描述】:

我有一个 CLI 应用程序的输出,看起来像:

Client ID Name       Value 1 Value 2
5         Joe last   5 1     5 2
6         Frank Last 6 1     6 2

问题,我可能想问的数据。

  1. 什么是 Frank 的 ID。 (返回:6)
  2. 数据的第 1 行中的 ID 是什么。 (返回:5)
  3. 当然我可以要求任何专栏

这些值是标准 CLI 输出,每列之间的空格数是随机的。输出的大小永远不会超过几百行。大多数时候少于 10 或 20 行。

如果有一个库可以将这些数据转换为字典,那就太好了,然后我就可以查询正确的列和行。

【问题讨论】:

    标签: arrays string multidimensional-array python-3.7


    【解决方案1】:

    嗯...这是一个可能的答案。我想做一些小事情,比如从列表的第一行中删除字段名称。还要使用列名来寻址字段,以便调用代码更易于阅读(例如 theList['Name'][1])。这个答案现在很好。我想不出一种简单的方法来准确计算列名,因为它们可能包含空格。调用者必须将其传入。

    def getFldPositions( cliData, fldList ):
        pos = [ ]
        for curItem in fldList:
            pos.append( data.find(curItem))
        pos.append( pos[-1] + len(fldList[-1] ))
        return pos
    
    def getCLIAsList( cliData, fldList ):
        pos = getPositions( cliData, fldList )
        newList = []
        for line in cliData.splitlines():
            newDict = [ ]
            for i, fld in enumerate(fldList):
                newDict.append( line[pos[i]:pos[i+1]].strip( ))
            newList.append(newDict)
        return newList
    
    def getCLIAsDict( cliData ):
        pos = getPositions( cliData, fldList )
        newList = []
        for line in cliData.splitlines():
            newDict = { }
            for i, fld in enumerate(fldList):
                newDict.update([ ( fld, line[pos[i]:pos[i+1]].strip() ) ])
            newList.append(newDict)
        return newList
    
    fldList = ['Client ID', 'Name', 'Value 1', 'Value 2']
    data    = 'Client ID Name       Value 1 Value 2\n' \
              '5         Joe last   5 1     5 2\n' \
              '6         Frank Last 6 1     6 2\n'
    theList = getCLIAsList( data, fldList )
    # theList = getCLIAsDict( data, fldList )
    
    print( theList )
    print( 'ID: '  + theList[1][0] )
    

    它返回这个:

    [['Client ID', 'Name', 'Value 1', 'Value 2'], ['5', 'Joe last', '5 1', '5 2'], ['6', 'Frank Last', '6 1', '6 2']]
    ID: 6
    

    【讨论】:

    • 请注意,这并不完美。我试图只提供 2 个字段来加快调用速度。使用:['客户 ID','名称']。在这种情况下,标题小于数据,我只从用户名中得到 4 个字符。我有 2 个变通方法,添加一堆空格作为真正的 hack 或添加第 3 列。我只关心前 2 列,而 CLI 实际上返回了 12 到 15 列。所以现在有点限制。如果我以后可以重温这个,我会的。
    猜你喜欢
    • 2020-07-23
    • 1970-01-01
    • 1970-01-01
    • 2021-02-07
    • 1970-01-01
    • 2015-09-16
    • 1970-01-01
    • 2022-01-22
    • 1970-01-01
    相关资源
    最近更新 更多