搜索GTF文件(textwraper文件)

2024-06-16 20:34:26 发布

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

我有一个包含RNA测序数据的GTF文件,在Shell中打开时如下所示:

1   Cufflinks   exon    12320750    12320851    .   +   .   gene_id "XLOC_000102"; transcript_id "TCONS_00014924"; exon_number "5"; gene_name "VPS13D"; oId "CUFF.308.3"; nearest_ref "ENST00000358136"; class_code "j"; tss_id "TSS819"; type "pc";
1   Cufflinks   exon    12321005    12321206    .   +   .   gene_id "XLOC_000102"; transcript_id "TCONS_00014924"; exon_number "6"; gene_name "VPS13D"; oId "CUFF.308.3"; nearest_ref "ENST00000358136"; class_code "j"; tss_id "TSS819"; type "pc";
1   Cufflinks   exon    12321958    12322137    .   +   .   gene_id "XLOC_000102"; transcript_id "TCONS_00014924"; exon_number "7"; gene_name "VPS13D"; oId "CUFF.308.3"; nearest_ref "ENST00000358136"; class_code "j"; tss_id "TSS819"; type "pc";

我需要写一个代码,当用户输入一个gene\u id时,它返回包含这个gene\u id的所有行

我写了这个代码:

def transcript_search(search_parameter):
for line in file:
   if search_parameter in line:
        return line
   else:
       print('Invalid entry')


f = open('/Users/labadmin/Desktop/example.gtf', 'r')
file = f.read()
gene_id = input("Enter the gene_id:")
transcript_search(gene_id)

当我运行这个代码时,即使我输入了列表中的id,它也找不到它。你知道吗

我还尝试使用f.split将此文件拆分为列表,但它给了我一个错误:

Traceback (most recent call last):
File "<pyshell#25>", line 1, in <module>
f.split()

我是Python新手,非常感谢您的帮助。你知道吗


Tags: namerefidnumbersearchlineoidtranscript
1条回答
网友
1楼 · 发布于 2024-06-16 20:34:26
def transcript_search(search_parameter,files):
   for line in files:
       if search_parameter in line:
          return line
      else:
        print('Invalid entry')


files = open('/Users/labadmin/Desktop/example.gtf', 'r')

gene_id = input("Enter the gene_id:")
transcript_search(gene_id,files)

不要使用文件。因为这是一个python关键字。您还需要将文件传递给函数。你知道吗

另外,您确定当它无效时您要打印但不返回任何内容吗?返回类型将是None。可能是你想要的,所以我没有改变。你知道吗

要只打印一次无效文件:

def transcript_search(search_parameter,files):
   for line in files:
       if search_parameter in line:
          return line
   #In this way invalid will only print after it has gone through all the lines and never returned.
   print('Invalid entry')

至于保存:

saved_lines = []

files = open('/Users/labadmin/Desktop/example.gtf', 'r')
gene_id = input("Enter the gene_id:")
#Append to list the saved entries.
saved_lines.append(transcript_search(gene_id,files))

之后,您可以使用files.writelines(list)将所有列表写入一行,或将它们打印到屏幕或任何您想要的内容。你知道吗

这会将带有ur search\u参数的所有行添加到一个列表中并返回该列表

def transcript_search(search_parameter,files):
   toreturn = []
   for line in files:
       if search_parameter in line:
          toreturn.append(line)
   if len(toreturn)>0:
       #Notice at how this returns an array of strings instead of one string.
       return toreturn
   print('Invalid entry')

相关问题 更多 >