- Details
- Parent Category: Programming Assignments' Solutions
We Helped With This Python Programming Homework: Have A Similar One?
Short Assignment Requirements
Assignment Description
Individual: Accessing the Internet WEEK 3
Review the program presented in Ch. 13.2 Program 163, "Writing Programs to Generate HTML," of Introduction to Computing and Programming in Python.
13.2 WRITING PROGRAMS TO GENERATE HTML
HTML itself is not a programming language. HTML can’t specify loops, conditionals, variables, data types, or anything else we’ve learned about specifying process. HTML is used to describe structure, not process.
That said, we can easily write programs to generate HTML. Python’s multiple ways of quoting strings come in really handy here!
Program 159: Generating a Simple
HTML Page
def makePage():
file=open("generated.html","wt")
file.write("""<!DOCTYPE html>
<html>
<head> <title>The Simplest Possible Web Page</title>
</head>
<body>
<h3>A Simple Heading</h3>
<p>Some simple text.</p>
</body>
</html>""")
file.close()
This works but it’s really boring. Why would you write a program to write what you can do with a text editor? You write programs for replicability, communicating process, and tailoring.
One of the most reasons that Web pages are generated are for catalogs. Web sites like Amazon and E-Bay don’t really have individual Web pages for each and every product. Rather they have some templates (essentially, functions that generate HTML) that they use to specify a few parameters and then generate a Web page.
Our first example is a function that takes as input a product name, an image file for the product, and a price. It generates a page that looks like Figure 13.7.
We call this function like this:
>>> makeCatalog("Seahorses","seahorses.jpg",32.75)
Program 160: A Catalog Page
Generator
def makeCatalog(product, image, price):
file=open(getMediaPath("catalog.html"),"wt")
body = """<!DOCTYPE html>
<html>
<head>
<title>Catalog Page for:"""+ product+'''</title>
</head>
<body>
<h3>'''+product+""" is the greatest!</h3>
<p>You are so lucky to have found this page!
You have the opportunity to buy """+product+"""
for the low, low price of $"""+str(price)+'''.
Just take a look at this beauty!
<img src="'''+image+'''" height = 100></p>
<p>Get one today!</p>
</body>
</html>'''
file.write(body)
file.close()
FIGURE 13.7
A sample catalog product page.
How It Works
Our function makeCatalog takes in a product, image, and price. We open a writable text file in the media folder named “catalog.html.” We then make up a really big string named body.
· We use triple quotes so that we can put in returns within the string. We sometimes use triple double-quotes and sometimes triple single-quotes in order to make it easier to understand the quote marks inside the HTML.
· We escape the string to insert the product name into the title Catalog Page for: (in our case) Seahorses. Clearly, the program expects a singular product, not a plural. The sentences are grammatically incorrect with a plural word as input. Computers will do just what we tell them to do, even if it’s wrong.
· We then expound upon the glories of this product, including the low, low price—which is a floating-point number, so we have to convert it into a string with str(price).
· We again escape the string to insert the actual filename for the image.
After formatting the whole body string, we write it to a file and close the file.
13.2.1 Making Home Pages
Imagine that you and a group of your friends decide to make home pages, and you all want them to look identical to one another except for a few small details. The general problem is like the catalog page generator that we just solved. Let’s make a home page creator that can create many home pages, just changing the name and interests.
Program 161: Initial Home Page
Creator
def makeHomePage(name, interest):
file=open(getMediaPath("homepage.html"),"wt")
file.write("""<!DOCTYPE html>
<html>
<head>
<title>"""+name+"""'s Home Page</title>
</head>
<body>
<h3>Welcome to """+name+"""'s Home Page</h3>
<p>Hi! I am """+name+""". This is my home page!
I am interested in """+interest+"""</p>
</body>
</html>""")
file.close()
Thus, executing makeHomePage("Barb","horses") will create:
<!DOCTYPE html>
<html>
<head>
<title>Barb’s Home Page</title>
</head>
<body>
<h3>Welcome to Barb’s Home Page</h3>
<p>Hi! I am Barb. This is my home page!
I am interested in horses</p>
</body>
</html>
Debugging
Tip: Write the HTML First
Programs to generate HTML can be confusing. Before you start trying to write one, write the HTML. Make up a sample of what you want the HTML to look like. Make sure that it works in your browser. Then write the Python function that generates that kind of HTML.
Modifying this program is painful, though. There is so much detail in the HTML and all that quoting is hard to get around. We’re better off using subfunctions to break up the program into pieces that are easier to manipulate. This is, again, an example of using procedural abstraction. Here’s a version of the program where we confine the parts that we’ll change most often to the top.
Program 162: Improved Home Page
Creator
def makeHomePage(name, interest):
file=open(getMediaPath("homepage.html"),"wt")
file.write(doctype())
file.write(title(name+"’s Home Page"))
file.write(body("""
<h3>Welcome to """+name+"""’s Home Page</h3> <p>Hi! I am
"""+name+""". This is my home page! I am interested in
"""+interest+"""</p>"""))
file.close()
def doctype():
return '<!DOCTYPE html>'
def title(titlestring):
return "<html><head><title>"+titlestring+"</title></head>"
def body(bodystring):
return "<body>"+bodystring+"</body></html>"
We can grab content for our Web pages from anywhere we want. Here is a program that can pull information out of a directory provided as input and generates an index page of those images (Figure 13.8). We’re not going to list the doctype() and other utility functions here—we’ll just focus on the part we care about. And that is how we should think about it—just the part we care about; we write doctype() once, then forget about it!
Figure 13.8 takes a little explaining. We ran the code that appears below by executing makeSamplePage(getMediaPath("")). Then, we opened the generated file “samples.html.” The generated page is all one line—which browsers have no trouble interpreting, but is hard for humans. We inserted some return characters to make it easier to read. The browser page to the right is what is seen when the HTML to the left is opened.
FIGURE 13.8
Creating a thumbnail page.
Program 163: Generate
a Thumbnail Page
import os
def makeSamplePage(directory):
samplesFile=open(directory+"/samples.html","wt")
samplesFile.write(doctype())
samplesFile.write(title("Samples from "+directory))
# Now, let’s make up the string that will be the body.
samples="<h3>Samples from "+directory+" </h3>"
for file in os.listdir(directory):
if file.endswith(".jpg"):
samples=samples+"<p>Filename: "+file
samples=samples+'<image src="'+file+'"height="100"></p>'
samplesFile.write(body(samples))
samplesFile.close()
We can get content to add to our home pages from a wide range of sources. We could scrape information to add to our pages. In the previous chapters, we have built koan generators and random sentence generator. We can add something like that to our homepage generator. The function tagline randomly returns a tag line (a signature line) to the bottom of the home page.
Program 164: Home Page Generator
with Random Tag Lines
import urllib
import random
import urllib
import random
def makeHomePage(name,interests):
file=open(getMediaPath("homepage.html"),"wt")
file.write(doctype())
file.write(title(name+"'s Home Page"))
text = "<h3>Welcome to "+name+"'s Home Page</h3> "
text += "<p>Hi! I am "+name+". This is my home page!"
text += " I am interested in "+interests+"</p>"
text += "<p>Random thought for the day: "+tagline()+"</p>"
file.write(body(text))
file.close()
def tagline():
tags = []
tags += #34;After all is said and done, more is said than done."]
tags += #34;Save time... see it my way."]
tags += ["This message transmitted on 100% recycled electrons."]
tags += ["Nostalgia isn’t what it used to be."]
tags += ["When you’re in up over your head, the first thing to do is close your mouth."]
tags += ["I hit the CTRL key but I’m still not in control!"]
tags += ["Willyoupleasehelpmefixmykeyboard?Thespacebarisbroken!"]
return random.choice(tags)
How It Works
Let’s walk through the whole large example.
· We are going to need both urllib and random in this function, so we import both of them at the top of our ProgramArea.
· Our main function is makeHomePage. We call it with a name and a string of interests, like this:
>>> makeHomePage("Dracula","bats and blood")
· At the top of makeHomePage, we open the HTML file we’re writing, then write out the doctype using the utility function. (It’s not listed here, but would have to be in the Program Area). We write out the title (using the title function) with the input name inserted.
· We build up the body of the page in the string variable text. We break it up across several lines to make it more readable. To do that, we use a shorthand in Python. The syntax += means “Append the string on the right to the string variable on the left.”
Read the line:
text += "<p>Hi! I am "+name+". This is my home page!"
as:
text = text + "<p>Hi! I am "+name+". This is my home page!"
Thus, we build up the body in the string text with a heading, a paragraph with the owner’s name, a statement about interests, and the random tag line. We write out the name and the return values from the functions by concatenating them into the middle of the HTML string. We then write that to the Web page body (using the body function).
· The function tagline creates a list of strings (using the same += shorthand, but with a list of strings), then randomly chooses one (using the library function random.choice). Each time tagline is called, it returns a string with a random tagline.
· >>> tagline()
· "I hit the CTRL key but I’m still not in control!"
· >>> tagline()
'Save time... see it my way.'
· Finally, back at makeHomePage, we close the HTML file, and we’re done.