Python脚本修改:调整XYZ文件坐标差值输出顺序
解决方案
假设你的XYZ文件中两个表格以空行分隔(这是多表格XYZ文件的常见格式),以下是修改后的Python3脚本,可实现先输出所有x坐标差值,再依次输出y、z坐标差值的要求:
def process_xyz(input_file, output_file): # 读取文件并过滤空行 with open(input_file, 'r') as f: lines = [line.strip() for line in f if line.strip()] # 拆分两个表格:假设两个表格行数一致,取中间位置分割 split_idx = len(lines) // 2 table1_lines = lines[:split_idx] table2_lines = lines[split_idx:] # 提取两个表格的坐标数据(第2、3、4列,对应索引1、2、3) coords1 = [] for line in table1_lines: parts = line.split() coords1.append([float(parts[1]), float(parts[2]), float(parts[3])]) coords2 = [] for line in table2_lines: parts = line.split() coords2.append([float(parts[1]), float(parts[2]), float(parts[3])]) # 分组计算差值:table2 - table1 diff_x = [] diff_y = [] diff_z = [] for c1, c2 in zip(coords1, coords2): diff_x.append(c2[0] - c1[0]) diff_y.append(c2[1] - c1[1]) diff_z.append(c2[2] - c1[2]) # 按要求顺序写入结果文件 with open(output_file, 'w') as f: # 写入所有x差值 for dx in diff_x: f.write(f"{dx:.6f}\n") # 保留6位小数,可按需调整精度 # 写入所有y差值 for dy in diff_y: f.write(f"{dy:.6f}\n") # 写入所有z差值 for dz in diff_z: f.write(f"{dz:.6f}\n") # 调用示例 if __name__ == "__main__": process_xyz("input.xyz", "diff_output.txt")
关键调整说明
- 差值分组收集:不再按行一次性输出每行的x/y/z差值,而是将所有x、y、z差值分别存入三个独立列表,为后续按列输出做准备
- 输出顺序重构:写入文件时先遍历输出全部x差值,再依次输出y、z差值,完全匹配需求
- 格式兼容处理:提前过滤空行,避免读取无效内容;坐标转换为浮点数确保计算精度
适配特殊分隔格式
如果你的XYZ文件两个表格不是按行数均分,而是用特定标记(比如TABLE 1、TABLE 2)分隔,可修改表格拆分逻辑:
# 示例:按自定义标记拆分表格 table1_lines = [] table2_lines = [] current_table = table1_lines for line in lines: if "TABLE 2" in line: # 替换为你的实际分隔标记 current_table = table2_lines continue current_table.append(line)
内容的提问来源于stack exchange,提问作者sumsum
相关产品推荐
相关产品推荐

