Program is still a mess and giving me lots of errors....sadly after many, many tries.
Tried changing file.write to f.write...after reading some other solutions. But know I am wrong.
f = 'file'
def main():
statement
statement
statement
statement
statement
def write_html_file():
statement
statement
statement
statement
statement
def write_html_head():
statement
statement
statement
statement
def write_html_body():
statement
statement
statement
statement
statement
print('Your web page is done')
main()
The following is a sample of what the user should see:
Enter your name: First Last
Describe yourself: I am trying to be a great python student...just not
there yet...
>After user has entered info, program should create n HTML file, with the input, for a web page. Following is a sample HTML content for the above input.
<html>
<head>
</head>
<body>
<center>
<h1> Firs Last </h1>
</center>
<hr />
I am trying to be a great python student...just not
there yet...
<hr />
</body>
</html>
You need to make your variables accessible from the other functions. If we declare f outside the main method, we are able to use the f.write on the other functions as well. Your code will run like this:
f = 'file'
name=input('Enter your name: ')
description=input('Describe yourself: ')
f = open('my_page.html','w')
def main():
write_html_file()
f.close()
def write_html_file():
f.write('<html>\n')
f.write('<head>\n')
f.write('<body>\n')
f.write('</html>\n')
def write_html_head():
f.write('<head>\n')
f.write('<title>My Personal Web Page</title>')
f.write('/<head>\n')
def write_html_body():
f.write('<body>\n')
f.write('\t<center>\n')
f.write('\t\t<h1>'+name+'</h1>\n')
f.write('\t<hr />\n')
f.write(description+'\n')
f.write('\t<hr />\n')
f.write('\t</center>\n')
f.write('</body>\n')
print('Your web page is done')
main()
Your output looks like this when running:
Enter your name: Sykezlol
Describe yourself: I like python
Your web page is done
<html>
<head>
<body>
</html>
<body>
<center>
<h1>Sykezlol</h1>
<hr />
I like python
<hr />
</center>
</body>
<head>
<title>My Personal Web Page</title>/<head>
remove the global file variable it is useless and for other functions you should pass a parameters that indicates the file , name and description like this :
def main():
name = input("Enter your name: ")
description = input("Describe yourself: ")
f = open("my_page.html", "w")
write_html_file(f, name, description)
f.close()
def write_html_file(f, name, description):
f.write(
f"<html>\n<head>\n</head>\n<body>\n<center>\n<h1>{name}</h1>\n</center>\n<hr />{description}<hr />\n</body>\n</html>"
)
main()
this should fix your attribute error
the html code could've been written in a better way but this will work and you don't need a several functions to write to a file just make one only.
you could split each line in a different write statement but make sure to use formatting to provide the name and description and that can be done with f at the beginning of a string or with .foramt() method.
Related
I am taking a beginning python class. Here is the question:
"Write a program that asks the user for his or her name, then asks the user to enter a sentence that describes himself or herself. Here is an example of the program’s screen:
Enter your name: Julie Taylor Enter
Describe yourself: I am a computer science major, a member of the
Jazz club, and I hope to work as a mobile app developer after I
graduate. Enter
Once the user has entered the requested input, the program should create an HTML file,
containing the input, for a simple Web page."
This is the code I have so far.
# Collect user data.
name = input("Enter your name: ")
content = input("Describe yourself: ")
# Create a file object.
f = open("program6.html", "w")
# Adding input data to the HTML file
f.write("<html>\n<head>\n<title> \nOutput Data in an HTML file \
</title>\n</head> <body><h1>name</h1>\
\n<h2>content</h2> \n</body></html>")
# Create a string to store the html script.
data = '''
<html>
<head>
</head>
<body>
<center>
<h1>name</h1>
</center>
<hr />
{content}
<hr />
</body>
</html>'''
# Saving the data into the HTML file
f.close()
I am struggling because when it creates the webpage, it inputs the words "name" and "content" versus utilizing the user input. How can I insert the users responses?
Thanks!
You can use f-strings. Do this by putting an f before the opening quotes. Here is your code with the applied changes.
# Collect user data.
name = input("Enter your name: ")
content = input("Describe yourself: ")
# Create a file object.
f = open("program6.html", "w")
# Adding input data to the HTML file
f.write(f"<html>\n<head>\n<title> \nOutput Data in an HTML file \
</title>\n</head> <body><h1>{name}</h1>\
\n<h2>{content}</h2> \n</body></html>")
# Create a string to store the html script.
data = f'''
<html>
<head>
</head>
<body>
<center>
<h1>{name}</h1>
</center>
<hr />
{content}
<hr />
</body>
</html>'''
# Saving the data into the HTML file
f.close()
place name and content in curly brackets and then use .format() or a leading f to format your string.
f.write(f"<html>\n<head>\n<title> \nOutput Data in an HTML file \
</title>\n</head> <body><h1>{name}</h1>\
\n<h2>{content}</h2> \n</body></html>")
Another alternate to bitflip's answer using the % operator:
# Adding input data to the HTML file
f.write("<html>\n<head>\n<title> \nOutput Data in an HTML file \
</title>\n</head> <body><h1>%s</h1>\
\n<h2>%s</h2> \n</body></html>" %(name, content))
This question already has answers here:
Sending data from HTML form to a Python script in Flask
(2 answers)
Closed 5 years ago.
Essentially what I am trying to do :
I have a simple HTML page with a Textarea to input a bunch of text, my use case is a single code on each line like below:
1234
5678
1456
etc.
Ideally I want to take that into Python and be able to work with the data and return the results. So lets start simple and say take each line as a separate entry and run it against a function to add the word "Hi" in front of it So the results are:
Hi 1234
Hi 5678
etc.
So far have this working example I found but I tend to break it anytime I try something.
Html:
<!DOCTYPE html>
<html lang="en">
<body>
<h1>Enter some text</h1>
<form action="submit" id="textform" method="post">
<textarea name="text">Hello World!</textarea>
<input type="submit" value="Submit">
</form>
</body>
</html>
Python:
From flask import Flask, request
app = Flask(__name__)
#app.route('/')
def main_form():
return '<form action="submit" id="textform" method="post"><textarea name="text">Hello World!</textarea><input type="submit" value="Submit"></form>'
#app.route('/submit', methods=['POST'])
def submit_textarea():
return "You entered: {}".format(request.form["text"])
if __name__ == '__main__':
app.run()
Example :
i try to extract the textarea to a string and then return that back to the page with :
x = format(request.form["text"])
return x
Any help or guidance would be appreciated!
You can access and store the text from textarea with the following lines :
#app.route('/submit', methods=['POST'])
def submit_textarea():
# store the given text in a variable
text = request.form.get("text")
# split the text to get each line in a list
text2 = text.split('\n')
# change the text (add 'Hi' to each new line)
text_changed = ''.join(['<br>Hi ' + line for line in text2])
# (i used <br> to materialize a newline in the returned value)
return "You entered: {}".format(text_changed)
When I type the code below, it gives me a blank HTML page. Even though I put a <h1> and a <a href> tag. Only the <title> tag is executed. Does anyone know why and how to fix it?
Code:
my_variable = '''
<html>
<head>
<title>My HTML File</title>
</head>
<body>
<h1>Hello world!</h1>
Click me
</body>
</html>'''
my_html_file = open(r"\Users\hp\Desktop\Code\Python testing\CH\my_html_file.html", "w")
my_html_file.write(my_variable)
Thanks in advance!
As #bill Bell said, it's probably because you haven't closed your file (so it hasn't flushed its buffer).
So, in your case:
my_html_file = open(r"\Users\hp\Desktop\Code\Python testing\CH\my_html_file.html", "w")
my_html_file.write(my_variable)
my_html_file.close()
But, this is not the right way to do it. Indeed, if an errors occurs in the second line for example, the file'll never get closed. So, you can use the with statement to make sure that it always is. (just as #Rawing said)
with open('my-file.txt', 'w') as my_file:
my_file.write('hello world!')
So, in fact, it's like if you did:
my_file = open('my-file.txt', 'w')
try:
my_file.write('hello world!')
finally:
# this part is always executed, whatever happens in the try block
# (a return, an exception)
my_file.close()
I have written a game in Python using the PyGame library that I am trying to embed into an HTML page to allow me to play in a web browser.
I am attempting to do this using the JavaScript library Skulpt. I have attached a test script below that successfully outputs the print statement below.
skulpt.html
<html>
<head>
<script src="assets/skulpt/skulpt.js" type="text/javascript"></script>
</head>
<body>
<textarea id="pythonCode">
print "I am python."
</textarea><br />
<pre id="output"></pre>
<script type="text/javascript">
function outf(text) {
var mypre = document.getElementById("output");
mypre.innerHTML = mypre.innerHTML + text;
}
var code = document.getElementById("pythonCode").value;
Sk.configure({output:outf});
eval(Sk.importMainWithBody("<stdin>",false,code));
</script>
</body>
</html>
Output of skulpt.html:
The issue that I am having is that when I use my game code instead of the simple print statement shown above it produces the error seen below;
I have included all relevant images to my web servers' directory at the correct path. I am unsure of why this error is being produced. Any help would be much appreciated, thanks!
Also, here is the attached Python game code (and a live demo of the error):
http://nicolasward.com/portfolio/skulpt.html
You have a lot of indentation on line 1 -> remember, in python, indentation always matters. Take away all those spaces/tabs on the first line and it should run.
How do I insert a variable into an HTML email I'm sending with python? The variable I'm trying to send is code. Below is what I have so far.
text = "We Says Thanks!"
html = """\
<html>
<head></head>
<body>
<p>Thank you for being a loyal customer.<br>
Here is your unique code to unlock exclusive content:<br>
<br><br><h1><% print code %></h1><br>
<img src="http://example.com/footer.jpg">
</p>
</body>
</html>
"""
Use "formatstring".format:
code = "We Says Thanks!"
html = """\
<html>
<head></head>
<body>
<p>Thank you for being a loyal customer.<br>
Here is your unique code to unlock exclusive content:<br>
<br><br><h1>{code}</h1><br>
<img src="http://example.com/footer.jpg">
</p>
</body>
</html>
""".format(code=code)
If you find yourself substituting a large number of variables, you can use
.format(**locals())
Another way is to use Templates:
>>> from string import Template
>>> html = '''\
<html>
<head></head>
<body>
<p>Thank you for being a loyal customer.<br>
Here is your unique code to unlock exclusive content:<br>
<br><br><h1>$code</h1><br>
<img src="http://example.com/footer.jpg">
</p>
</body>
</html>
'''
>>> s = Template(html).safe_substitute(code="We Says Thanks!")
>>> print(s)
<html>
<head></head>
<body>
<p>Thank you for being a loyal customer.<br>
Here is your unique code to unlock exclusive content:<br>
<br><br><h1>We Says Thanks!</h1><br>
<img src="http://example.com/footer.jpg">
</p>
</body>
</html>
Note, that I used safe_substitute, not substitute, as if there is a placeholder which is not in the dictionary provided, substitute will raise ValueError: Invalid placeholder in string. The same problem is with string formatting.
use pythons string manipulation:
http://docs.python.org/2/library/stdtypes.html#string-formatting
generally the % operator is used to put a variable into a string, %i for integers, %s for strings and %f for floats,
NB: there is also another formatting type (.format) which is also described in the above link, that allows you to pass in a dict or list slightly more elegant than what I show below, this may be what you should go for in the long run as the % operator gets confusing if you have 100 variables you want to put into a string, though the use of dicts (my last example) kinda negates this.
code_str = "super duper heading"
html = "<h1>%s</h1>" % code_str
# <h1>super duper heading</h1>
code_nr = 42
html = "<h1>%i</h1>" % code_nr
# <h1>42</h1>
html = "<h1>%s %i</h1>" % (code_str, code_nr)
# <h1>super duper heading 42</h1>
html = "%(my_str)s %(my_nr)d" % {"my_str": code_str, "my_nr": code_nr}
# <h1>super duper heading 42</h1>
this is very basic and only work with primitive types, if you want to be able to store dicts, lists and possible objects I suggest you use cobvert them to jsons http://docs.python.org/2/library/json.html and https://stackoverflow.com/questions/4759634/python-json-tutorial are good sources of inspiration
Hope this helps