2015-06-08 25 views
-2

我正在練習將HTML代碼插入到Python 2.7函數中。是否有人可以幫助給出答案了這樣一個問題:如何將HTML寫入函數?

編寫一個函數,有三個參數:在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() 

但是這並不把它在一個函數。我對這個問題要求執行的內容有點困惑。

+2

https://docs.python.org/2/tutorial/controlflow.html#defining-functions – jonrsharpe

回答

1

下面介紹如何編寫函數,並將變量傳遞給它。我在標題中添加了一個正則表達式,而不是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) 

內容的HTML文件:

$ cat hello.html 
<html><content><title>"This is a terrible title!"</title><p>"Hi brah!"</p></content></html>