替换文件内Unicode关键字脚本

该脚本用于在无外网环境中,对/docs目录下的HTML、MD、JSON和HTM文件进行内容替换。用户可自定义需替换的中文字符,脚本会将HTML文件中的Unicode编码转换为文本并进行替换,然后再转回Unicode格式。替换后的文件保存在指定文件夹,且会列出所有已替换的文件。

需求(只能使用内部库,无外网环境):

1、替换/docs 目录下html、md、json、htm的文件内容。

2、能交互自定义输入需要替换的值,并且支持中文字符替换。

3、将操作替换了的文件保存在指定文件夹里。

4、需要将 HTML文件里带有Unicode编码的内容转换成文本格式,然后进行替换并且而保持其他内容不变,最后在文本替换后再转换成Unicode格式。

import os
import fileinput

# 指定需要执行脚本进行替换文件的路径
dir_path = input("请输入目录路径(默认为 /docs): ") or "/docs"

# 获取需要替换的内容
old_name = input("请输入需要替换的名称: ")
new_name = input("请输入替换后的名称: ")

unicode_old = ''
for char in old_name:
    unicode_char = f'&#x{ord(char):x};'
    unicode_old += unicode_char
unicode_old = ''.join([c.upper() if c != 'x' else c for c in unicode_old])

unicode_new = ''
for char in new_name:
    unicode_char = f'&#x{ord(char):x};'
    unicode_new += unicode_char
unicode_new = ''.join([c.upper() if c != 'x' else c for c in unicode_new])

# 定义替换规则字典
replace_dict = {
    old_name: new_name,
    unicode_old: unicode_new
}

# 用于记录已经进行过内容替换的文件列表
replaced_files = []

# 遍历目录
for root, dirs, files in os.walk(dir_path):
    for file in files:
        # 获取文件扩展名
        file_extension = os.path.splitext(file)[1]

        # 筛选扩展名为 .md、.json、.html、.htm 和 .js 的文件
        if file_extension in ['.md', '.json', '.html', '.htm', '.js']:
            # 构建文件完整路径
            file_path = os.path.join(root, file)

            # 读取文件内容
            with fileinput.FileInput(file_path, inplace=True) as file:
                replaced = False  # 记录是否进行过内容替换
                for line in file:
                    # 遍历替换规则字典,逐一替换
                    for old_str, new_str in replace_dict.items():
                        # 替换字符串
                        line = line.replace(old_str, new_str)
                        replaced = True  # 标记为已经进行过内容替换
                    # 输出替换后的内容
                    print(line, end='')

                if replaced:
                    replaced_files.append(file_path)  # 将进行过内容替换的文件添加到列表中

print("已进行内容替换的文件列表:")
for file_path in replaced_files:
    print(file_path)

print("文件替换完成。")

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值