Fre*_*ins 5 html python encoding character-encoding
所以代码我将一个 HTML 文件复制到一个字符串中,然后将除普通文本和注释外的所有内容更改为小写。问题是它还会将åäö更改为 VS 代码无法识别的内容。我能找到的是它的编码问题,但在 py3 上找不到任何关于它的信息,我为 py2 找到的解决方案不起作用。任何帮助表示赞赏,如果您知道如何改进代码请告诉我。
import re
import os
text_list = []
for root, dirs, files in os.walk("."):
for filename in files:
if (
filename.endswith(".html")
):
text_list.append(os.path.join(root, filename))
for file in text_list:
file_content = open(f"{file}", "r+").read()
if file.endswith(".html"):
os.rename(file, file.replace(" ", "_").lower())
code_strings = re.findall(r"<.+?>", file_content)
for i, str in enumerate(code_strings):
new_code_string = code_strings[i].lower()
file_content = file_content.replace(code_strings[i], new_code_string)
else:
os.rename(file, file.replace(" ", "_").lower())
file_content = file_content.lower()
open(f"{file}", "r+").write(file_content)
Run Code Online (Sandbox Code Playgroud)
使用 Unicode 编码打开文件codecs。例子:
import codecs
codecs.open('your_filename_here', encoding='utf-8', mode='w+')
Run Code Online (Sandbox Code Playgroud)