在python中使用第一行作为变量

2024-10-01 11:22:09 发布

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

我想把这段代码改得更动态更具体。我想用每一列中的第一行信息作为标题来代替“numAtts”。这样,第一行也不会包含在@data下面的数据中。在

这是我的代码:

# -*- coding: UTF-8 -*-

import logging
from optparse import OptionParser
import sys

def main():
    LEVELS = {'debug': logging.DEBUG,
              'info': logging.INFO,
              'warning': logging.WARNING,
              'error': logging.ERROR,
              'critical': logging.CRITICAL}

    usage = "usage: arff automate [options]\n ."
    parser = OptionParser(usage=usage, version="%prog 1.0")

    #Defining options   
    parser.add_option("-l", "--log", dest="level_name", default="info", help="choose the logging level: debug, info, warning, error, critical")    

    #Parsing arguments
    (options, args) = parser.parse_args()

    #Mandatory arguments    
    if len(args) != 1:
        parser.error("incorrect number of arguments")

    inputPath = args[0]


    # Start program ------------------

    with open(inputPath, "r") as f:
        strip = str.strip
        split = str.split
        data = [split(strip (line)) for line in f]

###############################################################
## modify here##

    numAtts = len(data[0])
    logging.info(" Number of attributes : "+str(numAtts) )

    print "@RELATION relationData"
    print ""

    for e in range(numAtts):
        print "@ATTRIBUTE att{0} NUMERIC".format(e)

###############################################################

    classSet = set()
    for e in data:
        classSet.add(e[-1])

    print "@ATTRIBUTE class {%s}" % (",".join(classSet))
    print ""

    print "@DATA"

    for item in data:
        print ",".join(item[0:])


if __name__ == "__main__":
    main()

输入文件如下(制表符分隔):

^{pr2}$

输出文件(实际)如下:

^{3}$

所需的输出文件如下所示:

@RELATION relationData
@attribute 'att[F1]' numeric
@attribute 'att[F2]' numeric
@attribute 'att[F3]' numeric
@attribute 'att[F4]' numeric
@attribute 'att[F5]' numeric
@attribute 'att[F6]' {0,1}
@attribute 'class' STRING

@data
7209,3004,15302,5203,2,1,EXAMPLEA
6417,3984,16445,5546,15,1,EXAMPLEB
8822,3973,23712,7517,18,1,EXPAMPLEC

所以,正如您所看到的,我的代码已经差不多了,但是我不能/不确定如何将第一行标记为用于头的变量,并开始处理第2行的数据。在

因此,我的问题是:如何格式化输出以使用第一行作为标题? 有人有什么见解吗?谢谢!在


Tags: 代码inimportinfoparserfordatalogging
2条回答

您没有完全格式化所需的输出标题。这里

for e in range(numAtts):
        print "@ATTRIBUTE att{0} NUMERIC".format(e)

您只是将e的值格式化为输出。您需要访问data[0]。在

^{pr2}$

在以后的使用部分,您可以利用range/xrange来跳过0th索引。在

for e in range(1, numAtts):
    print ",".join(data[e][0:])

另外,我建议不需要在变量中存储str方法,您可以使用方法链接来获得所需的值。 而不是这样:

data = [split(strip (line)) for line in f]

使用这个:

data = [line.strip().split() for line in f]

已编辑********以包含此选项********

next还允许跳过第一行,从数据段开始,因此从第二行开始。在

next(iter(data))
for item in data[1:]:
    print ",".join(item[0:])

您可以利用python中的open返回生成器这一事实。f.readline()获取文件中的下一个可用行。它还导致生成器移到下一行,因此在列表理解中,它将跳过您已经用f.readline()读过的行。(请参阅此处的文档:https://docs.python.org/2/tutorial/inputoutput.html#methods-of-file-objects

with open(inputPath, "r") as f:
    strip = str.strip
    split = str.split
    titles = split(strip (f.readline())
    data = [split(strip (line)) for line in f]

相关问题 更多 >