我是python中的一个完整的新手。如果你可以帮助我会很棒。我的数据格式有点像这样。如果有人可以帮助我,我将不胜感激。
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
在以逗号分隔的值中,我试图仅提取" eventh"数字(第2,第4,第6,第8,第10等)根据第三列的+或 - 值排除并定位。
我想放置" eventh"从逗号分隔的数据中输出数字,如果是" +",则数字转到第四列并将该值加1,然后将其放在第5列。如果是" - ",则该数字为第五列,减去该值为1,并将其置于第四列。我知道这是一个复杂的解释,但如果有人能给我一个可以从哪里开始的想法,那将会很棒。感谢
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
edit2:经过大家的搜索和帮助后,我现在有了类似的东西。这给了我正确的输出,但我现在唯一的问题是我无法正确命名。 (即car.1,car.2,car.3,plane.1,plane.2 ....等等)有人可以让我深入了解这个问题吗?
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], ",")
print(comma)
fivess = comma[1::2]
print(fivess)
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\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\t%s\t%s\t%s\t%s\n' %(name, chr, type, start, stop))
getGenes(infileName, outfileName)
答案 0 :(得分:0)
按标签拆分每一行;然后在逗号上拆分最后一项(数字列表)。这将为您提供所有用于处理的位。
答案 1 :(得分:0)
您可以使用split方法来执行此操作:
txt = """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"""
lines = txt.split("\n")
for line in lines:
vehicle,vehicle_type,action,numbers = line.split('\t')
numbers_list = numbers.split(',')
您只能通过以下方式从列表中获取偶数:
even_locations_list = numbers_list[1::2] #starting from position 1 (the second object) and jumping 2 steps at a time)
答案 2 :(得分:0)
拆分的默认实现在任何空格(空格,制表符,你有什么)上拆分。
with open('infile.txt','r') as infile, open('outfile.txt','w') as outfile:
for line in infile:
name, group, op, elements = line.split()
elements = [int(i) for i in elements.split(',')[1::2]]
for idx, val in enumerate(elements):
if op == '-':
col4, col5 = val - 1, val
else:
col4, col5 = val, val + 1
output = "\t".join(map(str,
["{}.{}".format(name, idx+1), group, op, col4, col5]))
outfile.write(output + "\n")