Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/362.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何将HTML写入函数?_Python_Html_File_Python 2.7 - Fatal编程技术网

Python 如何将HTML写入函数?

Python 如何将HTML写入函数?,python,html,file,python-2.7,Python,Html,File,Python 2.7,我正在练习将HTML代码插入到Python 2.7函数中。有人能帮我回答这个问题吗 编写一个包含三个参数的函数:HTML的文件名 文件、HTML文档的标题及其内容。功能 应该基于这三个参数编写一个HTML文件。查看您的文件 在浏览器中 我倾向于这样做: filename = open("hello.html", "w") titleAndContent = '''<html><content><title>"TitleTitle"</title>&

我正在练习将HTML代码插入到Python 2.7函数中。有人能帮我回答这个问题吗

编写一个包含三个参数的函数:HTML的文件名 文件、HTML文档的标题及其内容。功能 应该基于这三个参数编写一个HTML文件。查看您的文件 在浏览器中

我倾向于这样做:

filename = open("hello.html", "w")
titleAndContent = '''<html><content><title>"TitleTitle"</title><p>"Hi brah!"</p></content></html> '''
filename.write(titleAndContent)
filename.close()
filename=open(“hello.html”、“w”)
titleAndContent=''“titlettle”“嗨,布拉!”

'' filename.write(标题内容) filename.close()

但这并不是把它放在函数中。我对这个问题到底要求我执行什么有点困惑。

下面是如何编写函数,并将变量传递给它。我在添加标题时使用了一个正则表达式,而不是replace(),因为我想留给您一些思考

#!/usr/bin/python

import re

def write_html(filename, title, content):

    # prepare the content... inject the title into the
    # content.

    content = re.sub(r'(?<=<title>").*?(?="</title>)', title, content)

    wfh = open(filename, 'w')
    wfh.write(content)
    wfh.close

if __name__ == '__main__':

    name = 'hello.html'
    title = "This is a terrible title!"
    content = '<html><content><title>"TitleTitle"</title>' \
              '<p>"Hi brah!"</p></content></html>'

    write_html(name, title, content)
#/usr/bin/python
进口稀土
def write_html(文件名、标题、内容):
#准备内容。。。将标题插入到
#内容。
content=re.sub(r'(?)?
$ cat hello.html 
<html><content><title>"This is a terrible title!"</title><p>"Hi brah!"</p></content></html>