IAR-YT-HEAT/DOC/convert_temp_table.py

41 lines
1.4 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import re
import csv
def convert_temp_table(input_file, output_file):
# 读取输入文件
with open(input_file, 'r', encoding='utf-8') as f:
lines = f.readlines()
# 准备三个列的数据存储
col1 = []
col2 = []
col3 = []
# 处理数据行(跳过标题行和最后一行元数据)
for line in lines[1:-1]:
# 使用正则表达式提取所有数字(包含小数)
numbers = re.findall(r'[-+]?\d*\.\d+|\d+', line)
# 每行应有6个数字3组温度+电阻)
if len(numbers) == 6:
# 分别添加到对应列
col1.append((float(numbers[0]), float(numbers[1]))) # 第一列
col2.append((float(numbers[2]), float(numbers[3]))) # 第二列
col3.append((float(numbers[4]), float(numbers[5]))) # 第三列
# 合并三列数据(先第一列,然后第二列,最后第三列)
data = col1 + col2 + col3
# 写入CSV文件
with open(output_file, 'w', newline='', encoding='utf-8') as f:
writer = csv.writer(f)
writer.writerow(['Temperature (℃)', 'Resistance (KΩ)']) # 写入表头
writer.writerows(data) # 写入所有数据
return data
if __name__ == "__main__":
input_file = "温度对照表.txt"
output_file = "温度对照表.csv"
data = convert_temp_table(input_file, output_file)
print(f"成功转换 {len(data)} 条数据到 {output_file}")