Python 搜索和替换不起作用

Python search and replace not working

我有以下简单的 HTML 文件。

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

我想将其读入 python 脚本并将 SUMMARY1 替换为文本 "hi there"(比方说)。我在 python

中执行以下操作
with open('test.html','r') as htmltemplatefile:
    htmltemplate = htmltemplatefile.read().replace('\n','')

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

以上代码将文件读入变量htmltemplate。 接下来我调用字符串对象的 replace() 函数将模式 SUMMARY1 替换为 "hi there"。但是输出似乎没有用 "hi there" 搜索和替换 SUMMARY1。这是我得到的。

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

有人能指出我做错了什么吗?

open() 不是 return 一个 str,它 return 是一个 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 库使这变得容易得多。