我想把这段代码改得更动态更具体。我想用每一列中的第一行信息作为标题来代替“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行的数据。在
因此,我的问题是:如何格式化输出以使用第一行作为标题? 有人有什么见解吗?谢谢!在
您没有完全格式化所需的输出标题。这里
您只是将
^{pr2}$e
的值格式化为输出。您需要访问data[0]
。在在以后的使用部分,您可以利用
range/xrange
来跳过0th
索引。在另外,我建议不需要在变量中存储
str
方法,您可以使用方法链接来获得所需的值。 而不是这样:使用这个:
已编辑********以包含此选项********
next
还允许跳过第一行,从数据段开始,因此从第二行开始。在您可以利用python中的
open
返回生成器这一事实。f.readline()
获取文件中的下一个可用行。它还导致生成器移到下一行,因此在列表理解中,它将跳过您已经用f.readline()
读过的行。(请参阅此处的文档:https://docs.python.org/2/tutorial/inputoutput.html#methods-of-file-objects)相关问题 更多 >
编程相关推荐