基于文件名匹配替换StaticMesh路径的Python脚本报错修复
修复脚本并实现静态网格路径替换功能
问题根源
File1中的空行导致脚本读取后执行索引或分割操作时触发IndexError: list index out of range,核心解决思路是先过滤空行,再构建名称-路径映射完成替换。
修复后完整脚本
import re import os def replace_static_meshes(file1_path, file2_path, output_path): # 读取File1,构建网格名称到完整路径的映射,自动过滤空行 mesh_path_map = {} with open(file1_path, 'r', encoding='utf-8') as f1: for line in f1: cleaned_line = line.strip() if not cleaned_line: continue # 跳过空行 # 提取路径中的网格名称(去除路径前缀和可能的扩展名) mesh_name = os.path.splitext(os.path.basename(cleaned_line))[0] mesh_path_map[mesh_name] = cleaned_line # 匹配目标行的正则表达式 mesh_pattern = re.compile(r"StaticMesh=StaticMesh'(.+?)'") # 处理File2并生成修改后的文件 with open(file2_path, 'r', encoding='utf-8') as f2, open(output_path, 'w', encoding='utf-8') as output_file: for line in f2: match_result = mesh_pattern.search(line) if match_result: target_name = match_result.group(1) # 找到对应路径则替换,否则保留原行 if target_name in mesh_path_map: replaced_line = mesh_pattern.sub(f"StaticMesh=StaticMesh'{mesh_path_map[target_name]}'", line) output_file.write(replaced_line) else: output_file.write(line) else: output_file.write(line) # 自定义文件路径后运行 if __name__ == "__main__": INPUT_FILE1 = "File1.txt" INPUT_FILE2 = "File2.txt" OUTPUT_FILE = "File2_modified.txt" replace_static_meshes(INPUT_FILE1, INPUT_FILE2, OUTPUT_FILE)
关键改进说明
- 空行过滤:读取File1时自动跳过空行,从根源避免空行引发的索引错误。
- 高效映射:用字典存储网格名称与完整路径的对应关系,替换时直接查找,提升处理效率。
- 精准匹配:通过正则表达式精准定位目标行,只替换符合格式的
StaticMesh行,不影响其他内容。 - 容错处理:若File2中的网格名称在File1中无对应路径,保留原行,避免数据丢失。
数据样例演示
File1.txt(含空行)
/Game/Meshes/SM_Rock01 /Game/Props/SM_Chair02 /Game/Vegetation/SM_Tree05
File2.txt
StaticMesh=StaticMesh'SM_Rock01' StaticMesh=StaticMesh'SM_Chair02' StaticMesh=StaticMesh'SM_Table03' OtherLine=NonMeshContent
运行后生成的File2_modified.txt
StaticMesh=StaticMesh'/Game/Meshes/SM_Rock01' StaticMesh=StaticMesh'/Game/Props/SM_Chair02' StaticMesh=StaticMesh'SM_Table03' OtherLine=NonMeshContent
内容的提问来源于stack exchange,提问作者S.T.A.L.K.E.R
相关产品推荐
相关产品推荐

