python按关键字列表查找并输出其所在行
网上一般是python中取文本中指定关键词的行并保存,如果需要批量提取会有些麻烦。
这里主要根据python 如何实现并行查找关键字所在的行?,代码如下:
#!/usr/bin/env python# -*- coding: utf-8 -*- __author__ = 'Shengwei Ma'__author_email__ = 'shengweima@'with open('3.txt', 'r') as f1:a = set(line.strip() for line in f1)with open('wheat_est_gi.fa.gff3', 'r') as f:for line in f:line1 = line.strip().split('\t')Name = line1[8].split(';')[1].split('=')[1]if Name in a:print line,
但是,实际操作中遇到一些问题及困惑
如:Error:IndexError: list index out of range,参考了IndexError: list index out of range的错误原因及解决方案
改正后的代码:
#设置输出文件名称,w为可写out = open('E:/test/find.txt','w') #输入关键字列表.txt,r为只读with open('E:/test/keyword.txt','r') as keyword: keyword2=set(line.strip() for line in keyword)#输入需要查找的文件with open('E:/test/G005.gff3','r') as gff:for line in gff:#分成9列line1=line.strip().split('\t',8)#print(line1)#解决IndexError: list index out of range问题try:#第9列,选取"ID="和".v3"之间的字段Name = line1[8].split('ID=')[1].split('.v3')[0]except:continue#print(Name)#判断name是否在keyword2里,如果是,则输出if Name in keyword2:#print (line)out.write(line)
相关阅读
.strip()
\r \t \n
.split()