在字符串中查找字符串并将其保存到BioPython上的文件

2024-09-28 03:16:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我想裁剪这个gi|1168222|sp|P46098.1|5HT3A_HUMAN来得到这个P46098,但是对于这类的任何序列gi|"RANDOM"|sp|"SEQUENCE"|"RANDOM"。 举个例子:

gi|1168222|sp|P46098.1|5HT3A_HUMAN
gi|1168223|sp|P35563.2|5HT3A_RAT
gi|112809|sp|P23979.1|5HT3A_MOUSE
gi|24211440|sp|O70212.1|5HT3A_CAVPO
gi|113067|sp|P22770|ACHA7_CHICK

我只想在sp|.之间,或者|如果没有.这就是我现在得到的:

from Bio import SeqIO
import re

handle = open("seqdumpsp.txt", "rU")
for record in SeqIO.parse(handle, "fasta") :
    line = record.id
    i1 = line.index('sp|')
    i2 = line.index('.')
    line = line.replace(line[:i1], '', line)
    line = line.replace(x[i2:], '')
    print line
handle.close()

但是这不起作用,因为我不能使用i1和i2来替换


Tags: importindexline序列randomrecordspreplace
3条回答
>>> line = 'gi|1168222|sp|P46098.1|5HT3A_HUMAN'

>>> line.split('|')
['gi', '1168222', 'sp', 'P46098.1', '5HT3A_HUMAN']

>>> line.split('|')[3]
'P46098.1'

>>> line.split('|')[3].split('.')
['P46098', '1']

>>> line.split('|')[3].split('.')[0]
'P46098'

你可以说line.split('|')[3]

通过字符串处理:

  1. 通过for循环迭代内容中的每一行
  2. 找到“sp |”世界。并设置起始索引
  3. 找到“.”字符和“|”字符并比较两者的索引
  4. 从步骤3中获取结束索引
  5. 为结果添加值

演示:

content = """gi|1168222|sp|P46098.1|5HT3A_HUMAN
gi|1168223|sp|P35563.2|5HT3A_RAT
gi|112809|sp|P23979.1|5HT3A_MOUSE
gi|24211440|sp|O70212.1|5HT3A_CAVPO
gi|113067|sp|P22770|ACHA7_CHICK"""

result = []

for line in content.split("\n"):
    start_index = line.find("sp|")
    if start_index==-1:
        continue

    #- +3 because lenght of sp| is 3
    end_index1 = line.find(".", start_index+3)
    end_index2 = line.find("|", start_index+3)

    if end_index1==-1 and end_index2==-1:
        continue
    elif end_index2==-1:
        end_index = end_index1
    elif end_index1==-1:
        end_index = end_index2
    elif end_index1 < end_index2:
        end_index = end_index1
    else:
        end_index = end_index2

    result.append(line[start_index+3:end_index])

print result

输出:

['P46098', 'P35563', 'P23979', 'O70212', 'P22770']

通过CSV

  1. 由于输入结构良好,所以使用CSV模块
  2. 通过CSV模块读取输入文件
  3. 使用列表理解和拆分方法得到最终结果

演示:

import csv

input_file = "dp-input1.csv"

with open(input_file) as fp:
    root = csv.reader(fp, delimiter='|')
    result = [row[3].split(".")[0] for row in root]
    #for row in root:
    #    tmp = row[3].split(".")[0]
    #    result.append(tmp)

print "Final result:-", result

输出:

Final result:- ['P46098', 'P35563', 'P23979', 'O70212', 'P22770']

相关问题 更多 >

    热门问题