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

标签 python html scripting utf-16 utf

我正在尝试使用下面的代码搜索和替换多个 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/

相关文章:

python - 如何用相同的代码满足不同的字符串格式化场景?

python在数组切片中找到高值(value)

bash - 脚本不显示目录中存在的文件名

shell - 这行在 shell 脚本中是什么意思?

python - 实现 tcp 的 accept() 函数

python - 在 Python 文档字符串中, `:obj:` 有什么作用?

html - 图片没有显示在 Github Pages 中?

html - 为什么这些 Twitter Bootstrap 导航栏类会发生冲突?

html - CSS 侧边栏始终全高

iphone - 哪些脚本语言解释器可以在 iOS 上运行?