pthon转换SR785频谱仪的代码
SR785频谱仪保存的文件格式是.78D,需要进行转换成记事本的格式,然后再对数据进行处理。
前提:
1:已经在C盘安装了SR785官网的转换程序。
2:python调用cmd主要用到的是subprocess模块,用代码前先测试一下这个模块能不能用,能用的话就可以继续进行。不行的话就需要安装一下request 库(一般都不用管,基本上安装python的时候就有了)
1 Python转换.78D文件。
import subprocess
# 使用 cmd.exe 执行 echo 命令
result = subprocess.run(['cmd.exe', '/c', 'echo', 'Hello, World!'], capture_output=True, text=True)
# 输出命令执行结果
print(result.stdout)
import os
import subprocess
# 定义要检索的文件夹路径
folder_path = r"C:\SRTRANS"
# 用于存储符合条件的文件名
file_list = []
# 检查指定的文件夹是否存在
if os.path.exists(folder_path):
# 遍历文件夹及其子文件夹,找出所有 .78D 文件
for root, dirs, files in os.walk(folder_path):
for file in files:
if file.lower().endswith('.78d'):
file_list.append(file)
print("找到的 .78D 文件列表:", file_list)
print("找到的 .78D 文件个数:", len(file_list))
# srtrans 可执行文件的完整路径
srtrans_path = os.path.join(folder_path, "srtrans.exe")
# 检查 srtrans 可执行文件是否存在
if not os.path.exists(srtrans_path):
print(f"srtrans 可执行文件 {srtrans_path} 不存在,请检查。")
else:
for file in file_list:
try:
# 构造完整的文件路径
full_file_path = os.path.join(folder_path, file)
# 构造转换命令
command = [srtrans_path, '/Oasc', full_file_path]
# 执行命令
result = subprocess.run(command, capture_output=True, text=True, check=True)
output = result.stdout
if "Finshed" in output:
print(f"文件 {file} 转换完成。")
else:
print(f"文件 {file} 转换可能出现问题,输出信息:{output}")
except subprocess.CalledProcessError as e:
print(f"处理文件 {file} 时出现错误,错误信息:{e.stderr}")
except Exception as e:
print(f"处理文件 {file} 时出现未知错误:{e}")
else:
print(f"指定的文件夹 {folder_path} 不存在。")
print("运行结束")
python的subprocess模块安装_mob64ca12f028ff的技术博客_51CTO博客
2.78D转换后的文件为.asc文件,需要再转换为.csv文件再进行绘图。
import csv
import numpy as np
import matplotlib.pyplot as plt
# 定义 ASC 文件路径和初始 CSV 文件路径
asc_file_path = r'C:\SRTRANS\srs012.asc'
csv_file_path = r'C:\SRTRANS\output.csv'
# 定义拆分后新的 CSV 文件路径
split_csv_file_path = r'C:\SRTRANS\output_split.csv'
# 步骤 1: 按行读取 ASC 文件并写入 CSV 文件
with open(asc_file_path, 'r', encoding='utf-8') as asc_file, open(csv_file_path, 'w', newline='', encoding='utf-8') as csv_file:
csv_writer = csv.writer(csv_file)
for line in asc_file:
csv_writer.writerow([line.strip()])
# 步骤 2: 提取数据部分(从 X[Hz] 行之后的两列数值)
data = []
in_data_section = False
with open(asc_file_path, 'r', encoding='utf-8') as asc_file:
for line in asc_file:
if line.strip().startswith(' X[Hz]'):
in_data_section = True
continue
if in_data_section:
parts = line.strip().split()
if len(parts) == 2:
try:
x = float(parts[0])
y = float(parts[1])
data.append([x, y])
except ValueError:
continue
# 步骤 3: 若提取到有效数据,计算第二列的最大值
if data:
data_array = np.array(data)
max_value = np.max(data_array[:, 1])
print(f"第二列的最大值是: {max_value}")
else:
print("未提取到有效数据,请检查文件格式。")
# 步骤 4: 若提取到有效数据,绘制图形
if data:
plt.plot(data_array[:, 0], data_array[:, 1])
plt.xlabel('X[Hz]')
plt.ylabel('Vrms/Hz^(1/...)')
plt.title('Data Plot')
plt.grid(True)
plt.show()
# 步骤 5: 将 CSV 文件中第 11 行到第 812 行根据空格拆分成两列
with open(csv_file_path, 'r', encoding='utf-8') as infile, \
open(split_csv_file_path, 'w', newline='', encoding='utf-8') as outfile:
reader = csv.reader(infile)
writer = csv.writer(outfile)
for i, row in enumerate(reader, start=1):
if 11 <= i <= 812:
line_content = row[0]
parts = line_content.split()
if len(parts) == 2:
writer.writerow(parts)
else:
writer.writerow(row)
else:
writer.writerow(row)
3.批量处理.asc文件
代码说明:
- 数据读取与预处理:
- 与之前的代码类似,先将
.asc
文件内容按行保存到.csv
文件,再将.csv
文件中第 11 - 812 行按空格拆分成两列保存到_split.csv
文件的第 6、7 列。 - 读取
_split.csv
文件的第 11 - 812 行,将第 6 列数据存储在column_6_data
列表,第 7 列数据存储在column_7_data
列表。
- 与之前的代码类似,先将
- 寻找第 7 列的 3 个最大值:
- 使用
np.argsort
函数对column_7_data
进行降序排序,得到排序后的索引。 - 遍历排序后的索引,对于每个索引,检查它与已选中的最大值索引对应的第 6 列数据的频率间隔是否至少为 50Hz。如果满足条件,则将该索引添加到
selected_max_indices
列表中。 - 当
selected_max_indices
列表长度达到 3 时,停止遍历。
- 使用
- 计算对应第 6 列的平均值:
- 如果找到了 3 个满足条件的最大值,提取这些最大值及其对应的第 6 列频率值。
- 计算这些频率值的平均值并输出。
- 绘图:
- 如果有有效数据,根据
_split.csv
文件的第 6、7 列数据绘制图形。
- 如果有有效数据,根据
import os
import csv
import numpy as np
import matplotlib.pyplot as plt
def process_asc_file(asc_file_path):
# 生成对应的 CSV 文件路径
csv_file_path = os.path.splitext(asc_file_path)[0] + '.csv'
split_csv_file_path = os.path.splitext(asc_file_path)[0] + '_split.csv'
# 步骤 1: 按行读取 ASC 文件并写入 CSV 文件
with open(asc_file_path, 'r', encoding='utf-8') as asc_file, open(csv_file_path, 'w', newline='',
encoding='utf-8') as csv_file:
csv_writer = csv.writer(csv_file)
for line in asc_file:
csv_writer.writerow([line.strip()])
# 步骤 2: 提取数据部分(从 X[Hz] 行之后的两列数值)
data = []
in_data_section = False
with open(asc_file_path, 'r', encoding='utf-8') as asc_file:
for line in asc_file:
if line.strip().startswith(' X[Hz]'):
in_data_section = True
continue
if in_data_section:
parts = line.strip().split()
if len(parts) == 2:
try:
x = float(parts[0])
y = float(parts[1])
data.append([x, y])
except ValueError:
continue
# 步骤 3: 若提取到有效数据,计算原数据第二列的最大值
if data:
data_array = np.array(data)
max_value = np.max(data_array[:, 1])
print(f"文件 {os.path.basename(asc_file_path)} 原数据第二列的最大值是: {max_value}")
else:
print(f"文件 {os.path.basename(asc_file_path)} 未提取到有效数据,请检查文件格式。")
# 步骤 4: 将 CSV 文件中第 11 行到第 812 行根据空格拆分成两列并保存到第 6、7 列
with open(csv_file_path, 'r', encoding='utf-8') as infile, \
open(split_csv_file_path, 'w', newline='', encoding='utf-8') as outfile:
reader = csv.reader(infile)
writer = csv.writer(outfile)
for i, row in enumerate(reader, start=1):
new_row = row.copy()
if 11 <= i <= 812:
line_content = row[0]
parts = line_content.split()
if len(parts) == 2:
# 确保新行有足够的列数
while len(new_row) < 7:
new_row.append('')
new_row[5] = parts[0]
new_row[6] = parts[1]
writer.writerow(new_row)
# 步骤 5: 在 _split.csv 文件中寻找第 7 列的 3 个最大值及对应第 6 列的平均值
column_6_data = []
column_7_data = []
with open(split_csv_file_path, 'r', encoding='utf-8') as csvfile:
reader = csv.reader(csvfile)
for i, row in enumerate(reader, start=1):
if 11 <= i <= 812 and len(row) >= 7:
try:
freq = float(row[5])
value = float(row[6])
column_6_data.append(freq)
column_7_data.append(value)
except ValueError:
continue
if len(column_7_data) >= 3:
sorted_indices = np.argsort(column_7_data)[::-1]
selected_max_indices = []
for index in sorted_indices:
if not selected_max_indices:
selected_max_indices.append(index)
else:
# 检查间隔是否至少为 50Hz
is_valid = True
for selected_index in selected_max_indices:
if abs(column_6_data[index] - column_6_data[selected_index]) < 50:
is_valid = False
break
if is_valid:
selected_max_indices.append(index)
if len(selected_max_indices) == 3:
break
if len(selected_max_indices) == 3:
max_values = [column_7_data[i] for i in selected_max_indices]
corresponding_freqs = [column_6_data[i] for i in selected_max_indices]
avg_freq = np.mean(corresponding_freqs)
print(f"文件 {os.path.basename(split_csv_file_path)} 第 7 列的 3 个最大值是: {max_values}")
print(f"对应的第 6 列频率的平均值是: {avg_freq}")
else:
print(f"文件 {os.path.basename(split_csv_file_path)} 未找到满足间隔至少 50Hz 的 3 个最大值。")
else:
print(f"文件 {os.path.basename(split_csv_file_path)} 第 7 列数据不足,无法找到 3 个最大值。")
# 步骤 6: 若提取到有效数据,根据第 6 列和第 7 列的数据画图
if data:
plot_data = []
with open(split_csv_file_path, 'r', encoding='utf-8') as csvfile:
reader = csv.reader(csvfile)
for i, row in enumerate(reader, start=1):
if 11 <= i <= 812 and len(row) >= 7:
try:
x = float(row[5])
y = float(row[6])
plot_data.append([x, y])
except ValueError:
continue
if plot_data:
plot_array = np.array(plot_data)
plt.plot(plot_array[:, 0], plot_array[:, 1])
plt.xlabel('Column 6 Data')
plt.ylabel('Column 7 Data')
plt.title(f'Plot for {os.path.basename(asc_file_path)}')
plt.grid(True)
plt.show()
# 指定要检索的文件夹路径
folder_path = r"your_file_adress" #替换你要分析的数据地址
# 检索文件夹下所有的 .asc 文件
asc_files = [os.path.join(folder_path, f) for f in os.listdir(folder_path) if f.lower().endswith('.asc')]
# 处理每个 .asc 文件
for asc_file in asc_files:
process_asc_file(asc_file)
该程序的bug:画图的部门好像一直不出图片。