2015-02-24 47 views
0

我有以下簡單的HTML文件。Python搜索和替換不工作

<html data-noop=="http://www.w3.org/1999/xhtml"> 
<head> 
<title>Hello World</title> 
</head> 
<body> 
SUMMARY1 
hello world 
</body> 
</html> 

我想讀這爲python腳本,並與文本「您好」(說)取代SUMMARY1。我這樣做的python

with open('test.html','r') as htmltemplatefile: 
    htmltemplate = htmltemplatefile.read().replace('\n','') 

htmltemplate.replace('SUMMARY1','hi there') 
print htmltemplate 

上面的代碼文件中讀入變量htmltemplate。 接下來我調用字符串對象的replace()函數以將「hi there」替換爲SUMMARY1模式。但是輸出似乎沒有搜索並用「hi there」代替SUMMARY1。這是我得到的。

<html data-noop=="http://www.w3.org/1999/xhtml"><head><title>Hello World</title></head><body>SUMMARY1hello world</body></html> 

有人能指出我在做什麼錯嗎?

+0

因爲open()不返回一個字符串對象,所以它返回一個文件對象。此外,你只打開文件閱讀(''r'')。這也是一個重複:http://stackoverflow.com/questions/39086/search-and-replace-a-line-in-a-file-in-python – dursk 2015-02-24 19:13:05

+0

我認爲我所做的錯誤是在行3.我將它更改爲htmltemplate = htmltemplate.replace('SUMMARY1','hi there'),它工作。 – broccoli 2015-02-24 19:35:52

+0

您還添加了'.read()'這不在你原來的文章中,並且有很大的改變。但不管怎樣,你仍然沒有真正編輯文件,''SUMMARY''仍然會出現在'test.html'中。 – dursk 2015-02-24 21:18:59

回答

2

open()不返回str,它返回一個file物體。此外,您只打開它閱讀('r'),而不是寫作。

你想要做的是一樣的東西:

new_lines = [] 
with open('test.html', 'r') as f: 
    new_lines = f.readlines() 
with open('test.html', 'w') as f: 
    f.writelines([x.replace('a', 'b') for x in new_lines]) 

fileinput庫使這是一個容易得多。

-1

字符串在Python是不可改變的,你應該重新分配你的變量

htmltemplate = htmltemplate.replace('SUMMARY1','hi there') 
+0

這是不正確的。 OP不處理字符串。 – dursk 2015-02-24 19:13:29