Using a fastq parser in Python (for instance the one provided by mappy
), it is rather straightforward to compute the sum of the lengths of the sequences present in a fastq file:
$ python3 -m pip install mappy # Only if mappy is not installed yet
$ python3 -c 'from mappy import fastx_read; print(sum(len(seq) for (_, seq, *_) in fastx_read("SRR077487_2.filt.fastq.gz")))'
2386161200
python3 -c '<insert some python code here>'
uses the -c
option of python3
that tells Python to execute the provided code (instead of starting an interactive interpreter, or running code present in a file).
Here the code has two steps (separated by a ;
, in a standard script, we could use a new line instead): first making the fastx_read
function available (because it is part of an optional module), second displaying the total length of the sequences.
fastx_read("path_to_a_file")
generates (name, sequence, quality) triplets when a fastq file is provided, or (name, sequence) pairs when a fasta file is provided.
The (_, seq, *_)
syntax is a form of "tuple unpacking" where we store the second element (the sequence) in a seq
variable.
The _
in is just a way to ignore the first element in the triplet/pair. The *_
is a way to ignore whatever is after the second element in the triplet/pair.
len(seq) for (_, seq, *_) in fastx_read("SRR077487_2.filt.fastq.gz")
is an expression representing the lengths (obtained with the predefined len
function) of the sequences present in the file "SRR077487_2.filt.fastq.gz"
.
So the code uses the predefined sum
function to compute the sum of values that are the lengths of the sequences extracted from the fastq file, and this is displayed using the print
function.
This should also work with either fasta or fastq format, and with or without gz compression.
I tested more parsers on a slightly different problem here: https://bioinformatics.stackexchange.com/a/380/292 and you can find inspiration with the other approaches proposed in the other answers there.