** Python的新成员,对不起**
我试图以一个给定的示例文件为例,使用函数将包含"A“或"T”或"G“或"C”(DNA链)的行添加到列表中。
示例文件:
gene1
ATGATGATGGCG
gene2
GGCATATC
CGGATACC
gene3
TAGCTAGCCCGC
在gene2下,我需要使用我的函数连接两个单独的行。
以下是我完成的功能:
def create(filename):
"""
Purpose: Creates and returns a data structure (list) to store data.
:param filename: The given file
Post-conditions: (none)
:return: List of data.
"""
new_list = []
f = open(filename, 'r')
for i in f:
if not('A' or 'T' or 'G' or 'C') in i:
new_list = new_list #Added this so nothing happens but loop cont.
else:
new_list.append(i.strip())
f.close()
return new_list我需要找到文件中有连续两行DNA ("GTCA")的部分,然后再将它们添加到我的列表中。
如果正确,则打印时的输出应读为:
['ATGATGATGGCG', 'GGCATATCCGGATACC', 'TAGCTAGCCCGC']提前感谢!
发布于 2019-06-06 04:46:20
雷吉斯去营救!
import re
def create(filename):
dna_regex = re.compile(r'[ATGC]+')
with open(filename, 'r') as f:
return dna_regex.findall(f.read().replace('\n', '')))
new_list = []
new_list += create("gene_file.txt")特别要注意的是,如果gene行包含A、T、G或C,则此实现可能会出现假阳性。
这样做是接收整个文件,删除换行符,然后查找所有只包含A、T、G或C的序列并返回它们。
发布于 2019-06-06 04:43:21
您可以使用set来检查一条线是否是DNA线,即只包含字母ACGT:
with open(filename) as f:
new_list = []
concat = False
for line in f:
if set(line.strip()) == {'A', 'C', 'G', 'T'}:
if concat:
new_list[-1] += line.strip()
else:
new_list.append(line.strip())
concat = True
else:
concat = False
# ['ATGATGATGGCG', 'GGCATATCCGGATACC', 'TAGCTAGCCCGC']发布于 2019-06-06 04:30:46
如果我们可以假设每个DNA片段都以一行作为前缀,那么我们可以利用takewhile函数对这些DNA线进行分组:
from itertools import takewhile
DNA_CHARS = ('A', 'T', 'G', 'C')
lines = ['gene1', 'ATGATGATGGCG', 'gene2', 'GGCATATC', 'CGGATACC', 'gene3', 'TAGCTAGCCCGC']
input_lines = iter(lines[1:])
dna_lines = []
while True:
dna_line = ''.join(takewhile(lambda l: any(dna_char in l for dna_char in DNA_CHARS),
input_lines))
if not dna_line:
break
dna_lines.append(dna_line)https://stackoverflow.com/questions/56470762
复制相似问题