我的数据看起来像这样:
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 列中取出“eventh”数字并将其放在第 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)
最佳答案
您实际上不必在 output.write()
行上这样做。理想情况下,您应该根据您的输入进行操作,这样您就可以先正确排序,然后再进行处理,而不必考虑顺序。这是我编写的代码,使用您的代码作为框架,但澄清/防错了一些事情:
import sys
infileName_s = sys.argv[1]
outfileName_s = sys.argv[2]
def getGenes(infileName, outfileName):
infile = open(infileName,"r")
outfile = open(outfileName, "w")
x = infile.read()
infile.close() # make sure to close infile and outfile
data = x.split('\n')
alldata = []
for line in data:
alldata.append(line.split())
alldata[-1][-1] = alldata[-1][-1].split(',')
alldata = sorted(alldata) # sort
mod_alldata = []
for line in alldata: # create data structures
for i in range(1, len(line[-1]), 2):
if line[2] == '+':
mod_alldata.append([line[0]+'.'+str(i/2+1), line[1], line[2], line[3][i], int(line[3][i])+1])
else:
mod_alldata.append([line[0]+'.'+str(i/2+1), line[1], line[2], int(line[3][i])-1, line[3][i]])
for line in mod_alldata: # write to file
outfile.write(line[0] + '\t' + line[1]+ '\t' + line[2] + '\t' + str(line[3]) + '\t' + str(line[4]) + '\n')
outfile.close()
getGenes(infileName_s, outfileName_s)
注意事项:
- 始终关闭您打开的文件。
- 注意变量作用域——您在内部以不同方式使用了
infileName
/infile
和outfileName
/outfile
在你的职能之外。 - 使用步长为 2 的
range
(就像我在这里所做的那样:range(1, len(line[-1]]), 2)
)非常棒-有助于遍历偶数索引,并且在奇数/空列表的情况下也很健壮。 - 我使用
sorted()
按字母顺序排序,因为我不知道您希望它们如何排序。如果您希望它们以不同的方式排序,请在评论中告诉我。
这是指定文本文件的输出:
bus.1 trans - 2 3
bus.2 trans - 4 5
bus.3 trans - 6 7
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
关于python:根据种类对每个条目进行编号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23221955/