繁体   English   中英

在创建 HTML 文件的 Python 代码中我哪里出错了? 我是否朝着正确的方向前进?

[英]Where am I going wrong in this Python code to create an HTML file? Am I going at all in the right direction?

我正在尝试使用 Python 制作 HTML 文档,但我什至不知道我是否朝着正确的方向前进。 我对 Python 和我的 HTML 经验都是我多年前参加的一门课程。 直到现在我才找到生成文档的位置,并且我看到它在某些时候实际上正在生成一个文件,但不再这样做了。 有人可以查看我的代码并告诉我我做错了什么以及我做对了什么吗? 我会根据需要回答任何问题。 Python 3.8。

def main():
inputName = str(input("Enter your name: "))
inputMajor = str(input("Enter your major: "))
inputCareer = str(input("Enter your future career and a brief description" + \
                        " of it: "))

return inputName, inputMajor, inputCareer

site = 'My Page.txt'
outfile = open(site, 'w+')

write_head()
write_body()

write_html()

outfile.close()

def write_html():

outfile.write('<html>\n')

write_head('My_Page.html')

write_body(write_html())

outfile.write('\n</html>\n')

定义写入头():

outfile.write('<head>\n')

outfile.write('<title>\n' + main() + '\n</title>\n')

outfile.write('\n</head>')

def write_body():

outfile.write('<body>')
outfile.write('<center>')
outfile.write('<h1>' + inputName + '</h1>')
outfile.write('<hr />')
outfile.write('<h2>' + inputMajor + '</h2>')
outfile.write('<hr />')
outfile.write(inputCareer)
outfile.write('</center>')
outfile.write('<hr />')
outfile.write('</body>')
outfile.write('</html>')

主要的()

唷,这里发生了很多事情,包括一些最终会递归的调用(例如一遍又一遍地调用自己)。

为了解决这个问题,请尝试在一个 go 中将所有这些作为脚本,没有函数或任何东西:

# Use the with statement to automatically close the file when you're done
with open('my_page.html', 'w') as f:
   f.write('<html>')
   f.write('<head>')
   f.write('</head>')
   f.write('</html>')

ETC...

完成这项工作后,您可以根据需要将写入行拆分为单独的函数,这样一开始事情就不会太混乱。

稍后,查看 Python 的其他一些功能,例如字符串格式。 这将允许您编写类似s = f'<h1>{my_string}</h1>'的字符串来自动插入my_string变量。

一个 function 返回一个 header 字符串可能如下所示:

def insert_header(header_string):
   return f'<h1>{header_string}</h1>'

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM