[英]How to write specific line lengths of a file?
我有这样的序列(超过9000):
>TsM_000224500
MTTKWPQTTVTVATLSWGMLRLSMPKVQTTYKVTQSRGPLLAPGICDSWSRCLVLRVYVDRRRPGGDGSLGRVAVTVVETGCFGSAASFSMWVFGLAFVVTIEEQLL
>TsM_000534500
MHSHIVTVFVALLLTTAVVYAHIGMHGEGCTTLQCQRHAFMMKEREKLNEMQLELMEMLMDIQTMNEQEAYYAGLHGAGMQQPLPMPIQ
>TsM_000355900
MESGEENEYPMSCNIEEEEDIKFEPENGKVAEHESGEKKESIFVKHDDAKWVGIGFAIGTAVAPAVLSGISSAAVQGIRQPIQAGRNNGETTEDLENLINSVEDDL
包含“>”的行是ID,带有字母的行是氨基酸(aa)序列。 我需要删除(或移至其他文件)低于40 aa和超过4000 aa的序列。 然后,生成的文件应仅包含该范围内的序列(> = 40 aa和<= 4K aa)。
我尝试编写以下脚本:
def read_seq(file_name):
with open(file_name) as file:
return file.read().split('\n')[0:]
ts = read_seq("/home/tiago/t_solium/ts_phtm0less.txt")
tsf = open("/home/tiago/t_solium/ts_secp-404k", 'w')
for x in range(len(ts)):
if ([x][0:1] != '>'):
if (len([x]) > 40 or len([x]) < 4000):
tsf.write('%s\n'%(x))
tsf.close()
print "OK!"
我做了一些修改,但是我得到的只是空文件或所有+9000序列。
在您的for循环中,由于使用range()
(即0,1,2,3,4...
),所以x
是一个迭代整数。 尝试以下方法:
for x in ts:
这将为您提供ts
每个元素x
另外,您不需要在x
周围加上括号; Python可以自己遍历字符串中的字符。 将括号放在字符串中时,将其放入列表中,因此,例如,如果尝试获取x
的第二个字符: [x][1]
,Python将尝试获取列表中的第二个元素你把x
放进去,就会遇到问题。
编辑:要包括ID,请尝试以下操作:
注意:我也将if (len(x) > 40 or len(x) < 4000)
更改为if (len(x) > 40 and len(x) < 4000)
-使用and
代替or
将给您结果您正在寻找。
for i, x in enumerate(ts): #NEW: enumerate ts to get the index of every iteration (stored as i)
if (x[0] != '>'):
if (len(x) > 40 and len(x) < 4000):
tsf.write('%s\n'%(ts[i-1])) #NEW: write the ID number found on preceding line
tsf.write('%s\n'%(x))
试试这个,简单易懂。 它不会将整个文件加载到内存中,而是逐行遍历文件。
tsf=open('output.txt','w') # open the output file
with open("yourfile",'r') as ts: # open the input file
for line in ts: # iterate over each line of input file
line=line.strip() # removes all whitespace at the start and end, including spaces, tabs, newlines and carriage returns.
if line[0]=='>': # if line is an ID
continue # move to the next line
else: # otherwise
if (len(line)>40) or (len(line)<4000): # if line is in required length
tsf.write('%s\n'%line) # write to output file
tsf.close() # done
print "OK!"
仅供参考,如果在unix环境中工作,也可以将awk用于单行解决方案:
cat yourinputfile.txt | grep -v '>' | awk 'length($0)>=40' | awk 'length($0)<=4000' > youroutputfile.txt
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.