我正在尝试使用python3将一个'fastq‘文件转换成一个以制表符分隔的文件。下面是输入:(第1-4行是我需要以制表符分隔格式打印的一条记录)。在这里,我尝试将每条记录读入一个列表对象:
@SEQ_ID
GATTTGGGGTT
+
!''*((((***
@SEQ_ID
GATTTGGGGTT
+
!''*((((***
使用以下命令:
data = open('sample3.fq')
fq_record = data.read().replace('@', ',@').split(',')
for item in fq_record:
print(item.replace('\n', '\t').split('\t'))
输出为:
['']
['@SEQ_ID', 'GATTTGGGGTT', '+', "!''*((((***", '']
['@SEQ_ID', 'GATTTGGGGTT', '+', "!''*((((***", '', '']
我在输出开始时得到一个空行,我不明白为什么??我知道有很多其他的方法可以做到这一点,但我需要在学习python的过程中找出其中的原因。谢谢
发布于 2013-06-08 19:20:49
当您将@
替换为,@
时,您需要在字符串的开头加上一个逗号(因为它以@
开头)。然后,当您拆分逗号时,在第一个逗号之前没有任何内容,因此这将在拆分中提供一个空字符串。基本上是这样的:
>>> print ',x'.split(',')
['', 'x']
如果你知道你的数据总是以@
开头,你可以跳过循环中的空记录。做for item in fq_record[1:]
就行了。
发布于 2013-06-09 02:20:25
您也可以逐行执行,而无需进行所有替换:
fobj = io.StringIO("""@SEQ_ID
GATTTGGGGTT
+
!''*((((***
@SEQ_ID
GATTTGGGGTT
+
!''*((((***""")
data = []
entry = []
for raw_line in fobj:
line = raw_line.strip()
if line.startswith('@'):
if entry:
data.append(entry)
entry = []
entry.append(line)
data.append(entry)
data
看起来像这样:
[['@SEQ_ID', 'GATTTGGGGTTy', '+', "!''*((((***"],
['@SEQ_ID', 'GATTTGGGGTTx', '+', "!''*((((***"]]
发布于 2013-06-09 19:20:39
感谢你们所有人的回答。作为一个初学者,我的主要问题是在.split(',')上出现了一个空行,我现在已经从概念上理解了这一点。所以我用python编写的第一个有用的程序是:
# this script converts a .fastq file in to .fasta format
import sys
# Usage statement:
print('\nUsage: fq2fasta.py input-file output-file\n=========================================\n\n')
# define a function for fasta formating
def format_fasta(name, sequence):
fasta_string = '>' + name + "\n" + sequence + '\n'
return fasta_string
# open the file for reading
data = open(sys.argv[1])
# open the file for writing
fasta = open(sys.argv[2], 'wt')
# feed all fastq records in to a list
fq_records = data.read().replace('@', ',@').split(',')
# iterate through list objects
for item in fq_records[1:]: # this is to avoid the first line which is created as blank by .split() function
line = item.replace('\n', '\t').split('\t')
name = line[0]
sequence = line[1]
fasta.write(format_fasta(name, sequence))
fasta.close()
随着我学到更多,答案中建议的其他事情对我来说会更清楚。再次感谢。
https://stackoverflow.com/questions/17002988
复制相似问题