python 中统计fasta文件scaffolds平均长度、最长scaffolds、最短scaffolds
001、利用列表实现
(base) root@PC1:/home/test# ls a.fasta test.py (base) root@PC1:/home/test# cat a.fasta ## 测试数据 >scaffold_1 CCCGGGTAAAACGGGTCTTCAAGAAAACGCTCCTCCGTTAATGCCGGCCGATTCAAATAA CCTCTGGCAACACCCGCTCCGGCAATGTATAGTTCACCGATACATCCAACAGGCAGCATC GGCCCNN >scaffold_2 CTGTTGCTCCTGTTGCTCCTGTTGATCCCGTTGCACCTGTTGGTCCAGTCGGTCCAATTC nnn >scaffold_3 TTGATCCAGTGGCTCCGGTTACTCCAGTTGATCCTGTTGCGCCTGTTGCTCCAGTTTCTC CGGTTGGTCCGGTTGATCCGGTTGCACCTGTTACTCCAGTGGCTCCGGTTACTCCCGTCG CTGTTGCTCCTGTTGCTCCTGTTGATCCCGTTGCACCTGTTGGTCCAGTCGGTCCAATTC (base) root@PC1:/home/test# cat test.py ## 测试脚本 #!/usr/bin/python in_file = open("a.fasta", "r") out_file = open("result.txt", "w") total_list = [] total_len = 0 for i in in_file: i = i.strip() if i[0] == ">": total_list.append(total_len) total_len = 0 else: total_len += len(i) total_list.append(total_len) total_list = total_list[1::] print("mean_sca", "max_sca", "min_sca", file = out_file, sep = "\t") print(sum(total_list)/len(total_list), max(total_list), min(total_list), file = out_file, sep = "\t") in_file.close() out_file.close() (base) root@PC1:/home/test# python test.py ## 执行脚本 (base) root@PC1:/home/test# ls a.fasta result.txt test.py (base) root@PC1:/home/test# cat result.txt ## 查看统计结果 mean_sca max_sca min_sca 123.33333333333333 180 63
002、利用字典实现
(base) root@PC1:/home/test# ls a.fasta test.py (base) root@PC1:/home/test# cat a.fasta ## 测试数据 >scaffold_1 CCCGGGTAAAACGGGTCTTCAAGAAAACGCTCCTCCGTTAATGCCGGCCGATTCAAATAA CCTCTGGCAACACCCGCTCCGGCAATGTATAGTTCACCGATACATCCAACAGGCAGCATC GGCCCNN >scaffold_2 CTGTTGCTCCTGTTGCTCCTGTTGATCCCGTTGCACCTGTTGGTCCAGTCGGTCCAATTC nnn >scaffold_3 TTGATCCAGTGGCTCCGGTTACTCCAGTTGATCCTGTTGCGCCTGTTGCTCCAGTTTCTC CGGTTGGTCCGGTTGATCCGGTTGCACCTGTTACTCCAGTGGCTCCGGTTACTCCCGTCG CTGTTGCTCCTGTTGCTCCTGTTGATCCCGTTGCACCTGTTGGTCCAGTCGGTCCAATTC (base) root@PC1:/home/test# cat test.py ## 测试脚本 #!/usr/bin/python in_file = open("a.fasta", "r") out_file = open("result.txt", "w") dict1 = dict() for i in in_file: i = i.strip() if i[0] == ">": key = i dict1[key] = 0 else: dict1[key] += len(i) print("max", "min", "mean", file = out_file, sep = "\t") print(max(dict1.values()), min(dict1.values()), sum(dict1.values())/len(dict1.values()), file = out_file, sep = "\t") in_file.close() out_file.close() (base) root@PC1:/home/test# python test.py ## 执行程序 (base) root@PC1:/home/test# ls a.fasta result.txt test.py (base) root@PC1:/home/test# cat result.txt ## 查看统计结果 max min mean 180 63 123.33333333333333