-
Notifications
You must be signed in to change notification settings - Fork 1
/
replace_fastaid.py
87 lines (71 loc) · 2.53 KB
/
replace_fastaid.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
#!/usr/bin/env python3
'''
replace_fastaid.py -- replace fastaid.
Date: 2021-05-10
Bugs: Any bugs should be reported to chenyanpeng1992@outlook.com
Usage:
replace_fastaid.py mapfile.txt multifasta.fna out.fna
'''
import sys
import argparse
def parse_args():
parser = argparse.ArgumentParser(
description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument('map',
metavar='<map.txt>',
type=str,
help='input filename, amino acid codons should be abbreviated or completed.')
parser.add_argument('fasta',
metavar='<multifasta.fna>',
type=str,
help='input file must be in FASTA format')
parser.add_argument('out',
metavar='<out.fna>',
type=str,
help='output file name')
parser.add_argument('--map_header',
action='store_true',
help='if --map_header, the map file with header line')
parser.add_argument('--oldid_field',
metavar='<int>',
type=int,
help='specify old field')
parser.add_argument('--new_id_field',
metavar='<int>',
type=int,
help='specify new id field')
args = parser.parse_args()
return args
def fastaid_map(mapfile, header=True):
'''group id and corresponding single-fasta id
'''
mapdict = {}
with open(mapfile) as mapfh:
counter = 0
for line in mapfh:
counter += 1
if header:
if counter == 1:
continue
new, _, raw = line.rstrip('\n').split()
mapdict[raw] = new
return mapdict
def fasta2dict(multifastafile):
fadict = {}
with open(sys.argv[2]) as multifastafh:
for line in multifastafh:
if line.startswith('>'):
fastaid = line.lstrip('>').split()[0].rstrip('\n')
fadict[fastaid] = []
else:
fadict[fastaid].append(line)
fadict = {k: ''.join(v) for k, v in fadict.items()}
return fadict
if __name__ == '__main__':
args = parse_args()
mapdict = fastaid_map(args.map, args.map_header)
fadict = fasta2dict(args.fasta)
with open(sys.argv[3], 'wt') as outfh:
for k, v in fadict.items():
outfh.write(f'>{mapdict[k]}\n{v}')