如何 use/convert sed 到 Python?

How to use/convert sed to Python?

是否可以将下面的给定行转换为 Python?

sed 's+forwarding_link+'$link'+g' first.html > index2.html

因为 link 是一个变量,它会在 Python

中保持原样

您将必须读取文件 first.html,使用 string.replace 替换匹配的字符串,然后将结果转储到 index2.html.

link = 'your link here'

with open('first.html') as infile:
    data = infile.read()

data = data.replace('forwarding_link', link)

with open('index2.html', 'w') as outfile:
    outfile.write(data)