gpt4 book ai didi

Python shell 在读取 (fasta) 文件时卡住

转载 作者:太空宇宙 更新时间:2023-11-03 19:21:30 26 4
gpt4 key购买 nike

我将首先展示我迄今为止拥有的代码:

def err(em):
print(em)
exit

def rF(f):
s = ""
try:
fh = open(f, 'r')
except IOError:
e = "Could not open the file: " + f
err(e)

try:
with fh as ff:
next(ff)
for l in ff:
if ">" in l:
next(ff)
else:
s += l.replace('\n','').replace('\t','').replace('\r','')
except:
e = "Unknown Exception"
err(e)
fh.close()
return s

由于某种原因,每当我尝试通过键入以下内容来读取文件时,python shell(我使用的是 3.2.2)就会卡住:

rF("mycobacterium_bovis.fasta")

rF 函数中的条件是为了防止读取以 ">"标记开头的每一行。这些行不是 DNA/RNA 代码(这是我试图从这些文件中读取的内容),应该忽略

我希望任何人都可以帮助我解决这个问题,我没有看到我的错误。

按照惯例,非常感谢!

编辑:*问题仍然存在!*这是我现在使用的代码,我删除了错误处理,无论如何这是一个奇特的补充,每当尝试读取文件时 shell 仍然会卡住。这是我现在的代码:

def rF(f):
s = ""
try:
fh = open(f, 'r')
except IOError:
print("Err")

try:
with fh as ff:
next(ff)
for l in ff:
if ">" in l:
next(ff)
else:
s += l.replace('\n','').replace('\t','').replace('\r','')
except:
print("Err")

fh.close()
return s

最佳答案

您从未定义过e
因此,您将得到一个被裸露的 except: 隐藏的 NameError。

这就是为什么指定异常是有益且健康的,例如:

try: 
print(e)
except NameError as e:
print(e)

但是,在像您这样的情况下,当您不一定知道异常(exception)是什么时,您至少应该使用 this method of displaying information about the error :

import sys
try:
print(e)
except: # catch *all* exceptions
e = sys.exc_info()[1]
print(e)

使用您发布的原始代码,将打印以下内容:

name 'e' is not defined
<小时/>

根据更新的信息进行编辑:
如果您有一个大文件,那么连接这样的字符串将会非常慢。
考虑将过滤后的信息写入另一个文件,例如:

def rF(f):
with open(f,'r') as fin, open('outfile','w') as fou:
next(fin)
for l in fin:
if ">" in l:
next(fin)
else:
fou.write(l.replace('\n','').replace('\t','').replace('\r',''))

我已经测试过上述代码可以在基于此处列出的格式规范的 FASTA 文件上运行:http://en.wikipedia.org/wiki/FASTA_format在 linux2 上使用 Python 3.2.2 [GCC 4.6.1]。

一些建议:

  • 从小事做起。完成一个简单的工作,然后添加一个步骤。
  • 在问题点添加 print() 语句。

此外,请考虑包含有关您尝试解析的文件内容的更多信息。这可能会让我们更容易提供帮助。

关于Python shell 在读取 (fasta) 文件时卡住,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9574379/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com