【发布时间】:2021-03-12 10:43:55
【问题描述】:
我正在尝试通过一个 txt 文件提取某些数字,将它们存储在一个列表中,然后使用这些数字提取存储在同一文件中的字符串。我的代码适用于我的一些文件,但突然出现列表索引超出范围错误。
这是我试图退出的文本文件部分的示例
/note="tRNA-Arg2"
tRNA 5573494..5573567
/locus_tag="Tery_R0035"
/product="tRNA-Arg"
或
tRNA complement(5630800..5630872)
/locus_tag="Tery_R0036"
/product="tRNA-His"
我正在尝试获取写在 tRNA 之后的数字。
这是我将数字提取到列表中的代码:
def extract_numbers(line):
#empty list
numbers = []
#creates a buffer (temporary space)
digits = ""
#for character in the line
for c in line:
#if its a digit
if c.isdigit():
#add character to the buffer
digits += c
#if it isnt a number
else:
#if there is something in the buffer (ie its not 0)
if len(digits) > 0:
#add the buffer to the numbers list
numbers.append(digits)
#empty again
digits = ""
#to make sure the last number is added to the list
if len(digits) > 0:
numbers.append(digits)
return numbers
并使用最后一个函数将其写入文件本身
def extract_tRNA(path):
with io.open(path, mode="r", encoding="utf-8") as file:
genome = file.readlines()
start_stop = []
for line in genome:
if "tRNA" in line[0:21]:
numbers = extract_numbers(line[21:])
start_stop.append((int(numbers[0]), int(numbers[1])))
return start_stop
然后,我用这个运行它:
work_dir = "/Users/..."
for path in glob.glob(os.path.join(work_dir, "*.gbff")):
sequences = extract_seq(path)
tRNA_loc = extract_tRNA(path)
extract_genes(path, tRNA_loc, sequences)
print(path)
是我的文件还是代码?我也不确定是否有更简单的方法来做同样的事情?
感谢您的帮助!
更新尝试正则表达式:
work_dir = "where my files are"
for path in glob.glob(os.path.join(work_dir, "*.gbff")):
with io.open(path, mode="r", encoding="utf-8") as file:
genome = file.readlines()
for line in genome:
if "tRNA" in line[0:21]:
p = re.compile('\d+') # \d means digit and + means one or more
m = p.findall(line)
print(m)
【问题讨论】:
-
对于您的第一个号码,字符串为
5573494..5573567。您是否希望 tRNA 是一个大数字55734945573567或数字列表[5573494, 5573567]' ? Or did you want long strings:"55734945573567"` 或字符串列表 `["5573494", "5573567"]' 可能有一种更简单的方法,具体取决于你想要什么。 -
数字总是以同样的方式分开吗?有两个点:
..?总是有两个数字吗? -
@rajah9 是的,总是有 2 个点和数字。我希望将两个数字分开在一个列表中,这就是我现在得到的!但不确定为什么它不起作用。我知道正则表达式可能更容易,但是当我尝试时我无法弄清楚模式
-
您需要缩进
print(m),使其位于m = p.findall(line)下方。