python按关键字列表查找并输出其所在行

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)

keyword.txt
相关阅读
.strip()
\r \t \n
.split()

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值