#!/usr/bin/env python """ code.py - Jim Mahoney, Sep 25, demo for python class Encode text using the classic 'ROT13' algorithm, which shifts each letter by 13 characters. (See for example http://en.wikipedia.org/wiki/ROT13 .) This version is fairly primitive, since this is early in the term, First, it assumes that all input consists *only* of the lowercase letters 'a' through 'z'. (A better version would also do uppercase, and skip any other characters.) Second, it works on files whose names are hard-coded into this program. To see it both encode and decode (which are the same, since 13+13=26), it converts plain.txt => coded.txt and coded.txt => decoded.txt Note the use of subroutines to break the task into several pieces. To run it : # create plain.txt $ ./code.py # look at coded.txt and decoded.txt To test the rot13 subroutine : $ python >>> import code rot13 : converting 'plain.txt' to 'encoded.txt' - done. rot13 : converting 'encoded.txt' to 'decoded.txt' - done. >>> code.rot13('impossible') 'vzcbffvoyr' """ def rot13(plain_text): """convert a string to one shifted by 13 characters""" coded_text = "" for char in plain_text: zero_to_25 = ord(char) - ord('a') coded_char = (zero_to_25 + 13) % 26; coded_text = coded_text + chr(coded_char + ord('a')) return coded_text def convert(in_filename, out_filename): print " rot13 : ", print " converting '" + in_filename + "' to '" + out_filename + "'", input_file = open(in_filename, 'r') output_file = open(out_filename, 'w') lines = input_file.readlines() for line in lines: line = line[0:-1] # remove last newline character # print "plain is '" + line + "'" coded_line = rot13(line) # print "code is '" + coded_line + "'" coded_line = coded_line + "\n" # add newline back in output_file.write(coded_line) print " - done." convert('plain.txt', 'encoded.txt') convert('encoded.txt', 'decoded.txt')