## page was renamed from Main/Python/2009/2008/Lesson05 ## page was renamed from Main/Python/2008/Lesson05 ## page was renamed from Courses/Python/Lesson05 == Занятие 5. == Краткое содержание: Практическое занятие. ---- <<TableOfContents>> === План рассказа === * Объявление: см. [[../Tasks|зачётные задания]], см. [[../Rating|рейтинговые задания]]. === Обязательно научиться === Написать одну хотя бы крохотную полноценную работающую программу. === Задачи === * см. список первых [[../Rating|рейтинговых заданий]] * см. задачу из [[../Lesson03|задания 3]] /* === Пример программы === Ни в коем случае не совеую использовать этот пример для задания r4. Это задание выполняется гораздо проще (на 6 баллов достаточно программы в 6 строк). {{{#!python #!/usr/bin/python # The line above is necessary to make program a valid UNIX script # Also necessary is format of newlines. If you use IDLE, it is probably # ok automatically. If you use FAR, you can convert newlines to UNIX # style either within FAR editor, or by command: sed -i 's/\r//g' file.py """ Simple FASTA manipulating example: find sequence by name in FASTA-file """ import sys # useful in many places in file class Fasta_Sequence(object): """ Sequence retrieved from FASTA file """ def __init__(self, string): r""" Create object from chunk of FASTA file; leading ">" optional Example: >>> seq = Fasta_Sequence(">SEQ1\nMTEITAA\nLVSVK\nAAEVAAQL") >>> print seq.name SEQ1 >>> print seq.headers None >>> print seq.sequence MTEITAALVSVKAAEVAAQL """ # Initialize all fields in case self.name = None self.id = None self.headers = None self.sequence = None # Parse first line first_line = string.split("\n", 1)[0] if len(first_line.strip()): self.name = first_line.split(" ", 1)[0].lstrip(">") # By definition only sequence name may be present if len(first_line.split(" ", 2)) == 3: self.id = first_line.split(" ", 2)[1] self.headers = first_line.split(" ", 2)[2].split(";") # Parse sequence self.sequence = "".join(string.split("\n")[1:]) def write(self, file): r""" Write sequence to a file Example: >>> seq = Fasta_Sequence(">SEQ1\nMTEITAA\nLVSVK\nAAEVAAQL") >>> seq.write(sys.stdout) >SEQ1 MTEITAALVSVKAAEVAAQL """ # Write headers first_line = ">" if self.name: # True only if self.name is not None or empty first_line += self.name if self.id: first_line += " " + self.id if self.headers: first_line += ";".join(self.headers) file.write(first_line + "\n") # Write sequence, 80 chars per line sequence = self.sequence[:] while len(sequence) > 0: file.write(sequence[:80] + "\n") sequence = sequence[80:] def main(): """ Check options, act accordingly """ if options.seq_name == None: print >>sys.stderr, "Option -s is mandatory!" # This funny form of 'print' is quite like sys.stderr.write(...) sys.exit(1) if options.fasta_file: input = open(options.fasta_file) else: input = sys.stdin if options.out_file: output = open(options.out_file, "w") else: output = sys.stdout for chunk in input.read().split("\n>"): seq = Fasta_Sequence(chunk) if seq.name == options.seq_name: seq.write(output) if __name__ == "__main__": import optparse parser = optparse.OptionParser() parser.add_option("-f", "--fasta-file", help="Input FASTA-file name") parser.add_option("-o", "--out-file", help="Output FASTA-file name") parser.add_option("-s", "--seq-name", help="Sequence name to search (mandatory)") parser.add_option("-t", "--test", action="store_true", help="Run self-tests") parser.add_option("-v", "--verbose", action="store_true", help="Verbose self-tests") options, args = parser.parse_args() if options.test or options.verbose: import doctest doctest.testmod() sys.exit() main () }}}