|
- import os
- import numpy as np
- import csv
- def traverse_folder(folder_path):
- # 遍历文件夹下的所有文件和子文件夹
- data = [["file","peak wavelength(nm)","half width(nm)"]]
- for root, dirs, files in os.walk(folder_path):
- for file in files:
- # 判断文件后缀是否为 .txt
- if file.endswith('.txt'):
- file_path = os.path.join(root, file)
- print(file_path) # 可根据需求进行处理
- peak,width = find_peak_and_width(file_path)
- data.append([file_path,peak,width])
- # 指定CSV文件路径
- #print(data)
- file_path = 'data.csv'
- # 打开CSV文件并写入数据
- with open(file_path, mode='w', newline='') as file:
- writer = csv.writer(file)
- writer.writerows(data)
- print("数据已成功存入CSV文件。")
-
- def find_peak_and_width(file_path):
- # 读取光谱文件数据
- # data = np.loadtxt(file_path,dtype=str,usecols = 7)
- data = np.array(read_variable_columns(file_path))
- #print(type(data))
- # 提取光谱曲线的 x 和 y 数据
- x = data[:, 0]
- y = data[:, 1]
- # 使用SciPy的find_peaks函数找到光谱曲线中的峰值
- peaks = np.array([np.argmax(y)])
- # 获取峰值波长和半峰宽
- peak_wavelength = x[peaks[0]]
- half_max_value = y[peaks[0]] / 2
- half_max_left, half_max_right = peak_widths(y, peaks, rel_height=half_max_value)
- # 打印峰值波长和半峰宽
- #print("峰值波长: {:.3f}".format(peak_wavelength))
- # print("半峰宽: {:.3f}".format(x[half_max_right] - x[half_max_left]))
- return peak_wavelength,x[half_max_right] - x[half_max_left]
-
- def peak_widths(y, peaks, rel_height):
- i = peaks[0]
- while y[i]>rel_height:
- i=i-1;
- half_max_left = i;
- i = peaks[0]
- while y[i]>rel_height:
- i=i+1;
- half_max_right = i;
- return half_max_left, half_max_right
- def read_variable_columns(file_path):
- # 存储每一行的数据
- data = []
- # 打开文件并读取行数据
- with open(file_path, 'r') as file:
- reader = csv.reader(file, delimiter='\t')
-
- for row in reader:
- #print(row)
- data.append(row)
- data = [[float(value) for value in row] for row in data[14:]]
- #print(data)
- return data
- traverse_folder('spectrum')
复制代码 |
|