Занятие 5.
Краткое содержание: Практическое занятие.
План рассказа
Объявление: см. зачётные задания, см. рейтинговые задания.
Обязательно научиться
Написать одну хотя бы крохотную полноценную работающую программу.
Задачи
см. список первых рейтинговых заданий
см. задачу из задания 3
Ни в коем случае не совеую использовать этот пример для задания r4. Это задание выполняется гораздо проще (на 6 баллов достаточно программы в 6 строк). Пример программы
1 #!/usr/bin/python
2 # The line above is necessary to make program a valid UNIX script
3 # Also necessary is format of newlines. If you use IDLE, it is probably
4 # ok automatically. If you use FAR, you can convert newlines to UNIX
5 # style either within FAR editor, or by command: sed -i 's/\r//g' file.py
6 """ Simple FASTA manipulating example: find sequence by name in FASTA-file
7 """
8 import sys # useful in many places in file
9
10 class Fasta_Sequence(object):
11 """ Sequence retrieved from FASTA file """
12
13 def __init__(self, string):
14 r""" Create object from chunk of FASTA file; leading ">" optional
15
16 Example:
17 >>> seq = Fasta_Sequence(">SEQ1\nMTEITAA\nLVSVK\nAAEVAAQL")
18 >>> print seq.name
19 SEQ1
20 >>> print seq.headers
21 None
22 >>> print seq.sequence
23 MTEITAALVSVKAAEVAAQL
24 """
25 # Initialize all fields in case
26 self.name = None
27 self.id = None
28 self.headers = None
29 self.sequence = None
30
31 # Parse first line
32 first_line = string.split("\n", 1)[0]
33 if len(first_line.strip()):
34 self.name = first_line.split(" ", 1)[0].lstrip(">")
35 # By definition only sequence name may be present
36 if len(first_line.split(" ", 2)) == 3:
37 self.id = first_line.split(" ", 2)[1]
38 self.headers = first_line.split(" ", 2)[2].split(";")
39
40 # Parse sequence
41 self.sequence = "".join(string.split("\n")[1:])
42
43 def write(self, file):
44 r""" Write sequence to a file
45
46 Example:
47 >>> seq = Fasta_Sequence(">SEQ1\nMTEITAA\nLVSVK\nAAEVAAQL")
48 >>> seq.write(sys.stdout)
49 >SEQ1
50 MTEITAALVSVKAAEVAAQL
51 """
52 # Write headers
53 first_line = ">"
54 if self.name: # True only if self.name is not None or empty
55 first_line += self.name
56 if self.id:
57 first_line += " " + self.id
58 if self.headers:
59 first_line += ";".join(self.headers)
60 file.write(first_line + "\n")
61
62 # Write sequence, 80 chars per line
63 sequence = self.sequence[:]
64 while len(sequence) > 0:
65 file.write(sequence[:80] + "\n")
66 sequence = sequence[80:]
67
68 def main():
69 """ Check options, act accordingly """
70 if options.seq_name == None:
71 print >>sys.stderr, "Option -s is mandatory!"
72 # This funny form of 'print' is quite like sys.stderr.write(...)
73 sys.exit(1)
74
75 if options.fasta_file:
76 input = open(options.fasta_file)
77 else:
78 input = sys.stdin
79
80 if options.out_file:
81 output = open(options.out_file, "w")
82 else:
83 output = sys.stdout
84
85 for chunk in input.read().split("\n>"):
86 seq = Fasta_Sequence(chunk)
87 if seq.name == options.seq_name:
88 seq.write(output)
89
90 if __name__ == "__main__":
91 import optparse
92
93 parser = optparse.OptionParser()
94 parser.add_option("-f", "--fasta-file", help="Input FASTA-file name")
95 parser.add_option("-o", "--out-file", help="Output FASTA-file name")
96 parser.add_option("-s", "--seq-name",
97 help="Sequence name to search (mandatory)")
98 parser.add_option("-t", "--test",
99 action="store_true", help="Run self-tests")
100 parser.add_option("-v", "--verbose",
101 action="store_true", help="Verbose self-tests")
102 options, args = parser.parse_args()
103
104 if options.test or options.verbose:
105 import doctest
106 doctest.testmod()
107 sys.exit()
108
109 main ()