This program will give you practice with reading from and writing to text files. It will read from a file containing the text to Hamlet's "To Be or Not to Be" speech, encode the text to a second file, and finally decode the encoded text to a third file. The first and third files should match upon the program's completion. A few points to remember while working:
- You are ONLY responsible for the file input/output code in the main function body.
- The encode and decode functions have already been written. You just need to know how to call them and use their return values.
- At a minimum, the completed program should work with the supplied text, but you may wish to try it with other text files, too. Just make sure those text files only contain alphanumeric characters and basic punctuation.
- As your program interacts with the text being read from and written to files...be aware of how the line endings are being incorporated and affecting appearance of output.
- Make sure you understand how to call the encode and decode functions:
- What parameters the functions take
- The types of the parameters
- The type returned by the functions
- Your program will be interacting with (i.e., reading from and/or writing to) three text files:
- Read From: The original file provided to you
- Write To/Read From: The file containing the encoded lines
- Write To: The final file containing the decoded lines, which should be mostly identical to the original file
+ Expand Code
import random
KEY = None
def init ():
"""Sets up the global KEY variable"""
global KEY
# Begin with list of non-alphanumeric
...
- Collapse Code
import random
KEY = None
def init ():
"""Sets up the global KEY variable"""
global KEY
# Begin with list of non-alphanumeric
chars = [' ', '.', ',', '!', '?', ';', ':', '\'', '"', "-"]
# Append digits to list
for ch in "0123456789":
chars.append(ch)
# Append upper and lowercase letters
for i in range (26):
chars.append(chr(ord('A') + i))
chars.append(chr(ord('a') + i))
random.shuffle(chars)
KEY = ''.join(chars)
def encode (offset, text):
"""Encodes a string of text using the KEY and the provided offset"""
result = ""
for ch in text:
if ch in ('\r', '\n'):
result += ch
else:
x = (KEY.index(ch) + offset) % len(KEY)
result += KEY[x]
return result
def decode (offset, text):
"""Decodes a string of text using the KEY and the provided offset"""
result = ""
for ch in text:
if ch in ('\r', '\n'):
result += ch
else:
x = (KEY.index(ch) - offset) % len(KEY)
result += KEY[x]
return result
def main():
"""A function to hold the main program code"""
init()
# I have set this value to 5, but
# you may change it, if you wish
OFFSET = 5
# Open your input file for reading, and
# open your output file for writing
#YOUR CODE GOES HERE:
print ("Original text lines:")
# For each line of the input file,
# you should...
# -print the line, with "--: " in front
# -encode the line by calling the encode function
# -write the encoded line to the output file
#YOUR CODE GOES HERE:
# CLOSE the input and output files:
print()
# Open the encoded file for reading, and
# open another output file for writing the
# decoded text.
#YOUR CODE GOES HERE:
print ("\nEncoded text lines:")
# While reading in the lines of the current
# input file -- the encoded file -- you should...
# -print the line, with "--: " in front
# -decode the line by calling the decode function
# -write the decoded line to the new output file
#YOUR CODE GOES HERE:
# CLOSE the input and output files:
print()
print ("\nDecoded text lines:")
# Open the decoded file for reading:
# Print each line, with "--: " in front:
# Close the file:
print()
# Run the main program code
main ()
input("\n\nPress the enter key to exit.")
- Collapse Code
Download the following file into the same folder as your program file: original_file.txt
As long as you are using the provided text file as your original input file, then the output should look like it does below. However, if you use different text files for input, then the output will look different each time you run the program -- but the original file and the decoded version should still match.
Program output:
+ Expand Output
Original text lines:
--: To be, or not to be--that is the question:
--: Whether 'tis nobler in the mind to suffer
--: The slings and arrows of outrageous fortune
--: Or to take arms against a sea of troubles
--: And by opposing end them. To die, to sleep--
--: No more--and by a sleep to say we end
--: The heartache, and the thousand natural shocks
--: That flesh is heir to. 'Tis a consummation
...
- Collapse Output
Original text lines:
--: O, then I see Queen Mab hath been with you.
--: She is the fairies' midwife, and she comes
--: In shape no bigger than an agate stone
--: On the forefinger of an alderman,
--: Drawn with a team of little atomies
--: Over men's noses as they lie asleep;
--: Her wagon spokes made of long spinners' legs,
--: The cover, of the wings of grasshoppers;
--: Her traces, of the smallest spider web;
--: Her collars, of the moonshine's wat'ry beams;
--: Her whip, of cricket's bone; the lash, of film;
--: Her wagoner, a small grey-coated gnat,
--: Not half so big as a round little worm
--: Pricked from the lazy finger of a maid;
--: Her chariot is an empty hazelnut,
--: Made by the joiner squirrel or old grub,
--: Time out o' mind the fairies' coachmakers.
Encoded text lines:
--: mcxTsG0xYxRGGxq5GG0x9d1xsdTsx1GG0xWrTsxwp5n
--: ,sGxrRxTsGxVdrErGRPx8rlWrVGcxd0lxRsGxNp8GR
--: Y0xRsdhGx0px1r GExTsd0xd0xd dTGxRTp0G
--: m0xTsGxVpEGVr0 GExpVxd0xdAlGE8d0c
--: SEdW0xWrTsxdxTGd8xpVxArTTAGxdTp8rGR
--: mZGEx8G0PRx0pRGRxdRxTsGwxArGxdRAGGhO
--: XGExWd p0xRhpJGRx8dlGxpVxAp0 xRhr00GERPxAG Rc
--: fsGxNpZGEcxpVxTsGxWr0 RxpVx EdRRsphhGERO
--: XGExTEdNGRcxpVxTsGxR8dAAGRTxRhrlGExWG1O
--: XGExNpAAdERcxpVxTsGx8pp0Rsr0GPRxWdTPEwx1Gd8RO
--: XGExWsrhcxpVxNErNJGTPRx1p0GOxTsGxAdRscxpVxVrA8O
--: XGExWd p0GEcxdxR8dAAx EGwHNpdTGlx 0dTc
--: epTxsdAVxRpx1r xdRxdxEp50lxArTTAGxWpE8
--: aErNJGlxVEp8xTsGxAdbwxVr0 GExpVxdx8drlO
--: XGExNsdErpTxrRxd0xG8hTwxsdbGA05Tc
--: 9dlGx1wxTsGxKpr0GExRy5rEEGAxpExpAlx E51c
--: fr8Gxp5TxpPx8r0lxTsGxVdrErGRPxNpdNs8dJGERn
Decoded text lines:
--: O, then I see Queen Mab hath been with you.
--: She is the fairies' midwife, and she comes
--: In shape no bigger than an agate stone
--: On the forefinger of an alderman,
--: Drawn with a team of little atomies
--: Over men's noses as they lie asleep;
--: Her wagon spokes made of long spinners' legs,
--: The cover, of the wings of grasshoppers;
--: Her traces, of the smallest spider web;
--: Her collars, of the moonshine's wat'ry beams;
--: Her whip, of cricket's bone; the lash, of film;
--: Her wagoner, a small grey-coated gnat,
--: Not half so big as a round little worm
--: Pricked from the lazy finger of a maid;
--: Her chariot is an empty hazelnut,
--: Made by the joiner squirrel or old grub,
--: Time out o' mind the fairies' coachmakers.
- Collapse Output
Questions: - How did the process of creating these programs go for you?
- What were your main challenges and how did you overcome them?
- What did you learn that may be of use as you move along in this class?