/home/wpollock1/public_html/restricted/ShellScripting/proj-4 encode HTML model solution.txt
#!/usr/bin/python3
""" text2html.py is a filter that converts text files into valid XHTML files.
Written 4/2014 by Wayne Pollock, Tampa Florida USA
"""
import re, sys
def main ():
if len( sys.argv[1:] ) == 0:
sys.argv.insert( 1, '-' )
for filename in sys.argv[1:]:
encode( filename )
print()
def encode( filename ):
if filename == '-':
filename = "STDIN"
file = sys.stdin
else:
file = open( filename )
# Print the XHTML prolog, substituting the filename for "{}":
print( '''<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>{}</title>
</head>
<body>
<pre>''' .format(filename) )
# Encode special characters with the equivalent XHTML entities:
# (Note, it is important to substitute "&" first!)
for line in file:
line = re.sub( '&', '&', line, 0)
line = re.sub( '<', '<', line)
line = re.sub( '>', '>', line)
print( line, end="" )
# Print the XHTML epilog:
print( ''' </pre>
</body>
</html>''')
if file != sys.stdin:
file.close()
if __name__ == "__main__": main()