gpt4 book ai didi

python - 使用 python 搜索/替换 html 文件中的文本

转载 作者:太空宇宙 更新时间:2023-11-03 15:13:00 25 4
gpt4 key购买 nike

我正在尝试使用下面的代码搜索和替换多个 html 文件中的文本,它适用于 .txt,而不适用于转换为 .txt 的 html。是utf-16的问题吗?我怎样才能让它发挥作用?

import os
directory ="/Users/sinanatra/PYTHON_STUFF/MSN/0/"

replacement = "test"
for dname, dirs, files in os.walk(directory):
for fname in files:
fpath = os.path.join(dname, fname)
with open(fpath) as f:
s = f.read()
s = s.replace("head", replacement)
with open(fpath, "w") as f:
f.write(s)

最佳答案

如果你使用utf-16那么你需要

s.read().decode('utf-16') 对于写入,您将需要:

f.write(s.encode('utf16'))

关于python - 使用 python 搜索/替换 html 文件中的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44084650/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com