import xml.etree.ElementTree as et import re import os from bs4 import BeautifulSoup def read_resx_to_dict(path): tree = et.parse(path) root = tree.getroot() res_dict_x = {} for data in root.findall('data'): name = data.attrib['name'] value = data.find('value').text res_dict_x[value] = name return res_dict_x def replace_text(content, old_text, new_text): # 替换在标签之间的文本 # content = re.sub(r'>(.*?)' + re.escape(old_text) + r'(.*?)<', # f'>\\1\\2<', # content) content = re.sub(r'>' + re.escape(old_text) + r'<', f'><', content) # # 替换在标签之间的文本2 # content = content.replace(old_text+"<",'<') # 替换在属性值中的文本 content = re.sub(r'"([^"]*)"', lambda m: f'\"<%$ Resources:Lan,{new_text}%>\"' if m.group(1) == old_text else m.group(0), content) return content def replace_text_in_aspx(aspx_file, res_dict): with open(aspx_file, 'r', encoding='utf-8', newline='') as file: aspx_content = file.read() for old_text, new_text in res_dict.items(): if new_text != "": aspx_content = replace_text(aspx_content, old_text, new_text) with open(aspx_file, 'w', encoding='utf-8', newline='') as file: file.write(aspx_content) print(f"{aspx_file} ...替换完成") def get_aspx_files(directory): aspx_files = [] for root, dirs, files in os.walk(directory): for file in files: if file.endswith('.aspx'): aspx_files.append(os.path.join(root, file)) return aspx_files #示例调用 resx_path = "E:\\work_zhj\\Chinese2English\\ZHGL.resx" directory_path = 'E:\work\project\成达\sggl_cd\SGGL\FineUIPro.Web\ZHGL' res_dict = read_resx_to_dict(resx_path) print("资源文件分析完成") print("开始替换") aspx_files = get_aspx_files(directory_path) for file in aspx_files: replace_text_in_aspx(file, res_dict) # 替换 单个aspx 文件中的文本 # resx_path = "E:\\work_zhj\\Chinese2English\\rest.resx" # # res_dict = read_resx_to_dict(resx_path) # # directory_path = "E:\work\project\成达\sggl_cd\SGGL\FineUIPro.Web\index.aspx" # # replace_text_in_aspx(directory_path, res_dict)