python按关键字列表查找并输出其所在行
网上一般是python中取文本中指定关键词的行并保存,如果需要批量提取会有些麻烦。
这里主要根据python 如何实现并行查找关键字所在的行?,代码如下:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'Shengwei Ma'
__author_email__ = 'shengweima@icloud.com'
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)