【发布时间】:2014-06-06 23:12:58
【问题描述】:
我的数据看起来像这样:
car trans + 1,4,6,8
plane trans + 3,5,7,9,4,3
train trans - 2,4,6,7
bus trans - 1,3,4,5,6,7,8
这需要按以下格式组织。我基本上想从第 4 列中获取“第 7 个”数字并将其放在第 4 列,它是“+”,如果它是“-”,则放在第 5 列。然后,如果它的“+”我想将其值加 1 并将其放在第 5 列中。如果是“-”,我想减 1 放在第 4 列
car.1 trans + 4 5
car.2 trans + 8 9
plane.1 trans + 5 6
plane.2 trans + 9 10
plane.3 trans + 3 4
train.1 trans - 3 4
train.2 trans - 6 7
bus.1 trans - 2 3
bus.2 trans - 4 5
bus.3 trans - 6 7
以下是我现在拥有的代码。这给出了我想要的输出,但唯一的问题是第一列上的名称没有按我想要的顺序排列。 (car.1,car.2) 我知道我必须将它指向 output.write() 行,但我不确定如何创建一个字符串,该字符串将对原始数据中逗号分隔值的元素进行编号。请帮帮我!
import sys
import string
infileName = sys.argv[1]
outfileName = sys.argv[2]
def getGenes(infile, outfile):
infile = open(infileName,"r")
outfile = open(outfileName, "w")
while 1:
line = infile.readline()
if not line: break
wrds = string.split(line)
comma = string.split(wrds[3], ",")
fivess = comma[1::2]
if len(wrds) >= 2:
name = wrds[0]
chr = wrds[1]
type = wrds[2]
print(type)
if type == "+":
for jj in fivess:
start = jj
stop = string.atoi(jj)+1
outfile.write('%s%s\t%s\t%s\t%s\t%s\n' %(name, , chr, type, start, stop))
elif type == "-":
for jj in fivess:
stop = jj
start= string.atoi(jj)-1
outfile.write('%s%s\t%s\t%s\t%s\t%s\n' %(name, ,chr, type, start, stop))
getGenes(infileName, outfileName)
【问题讨论】:
-
您是否考虑过将处理后的数据放入
list,然后使用list.sort()给出您想要的顺序,然后再将其写回? -
@jonrsharpe 我只是想提出完全相同的建议。如果默认的文本顺序排序不符合标准(乍一看似乎应该如此),您可以使用
key参数传入一个函数进行比较
标签: python sorting file-io formatting