准备一个mgf文件
BEGIN IONS
TITLE=Cont-1.49.49. File:"Cont-1.raw", NativeID:"controllerType=0 controllerNumber=1 scan=49"
RTINSECONDS=0.439872
PEPMASS=571.50964
CHARGE=0
388.9727783 164.2929382324
428.9584045 150.5850830078
447.0253906 202.8974914551
464.6489563 733.7127075195
474.4710083 263.7313232422
481.8546143 616.1991577148
491.6105042 1123.8068847656
497.7576294 1198.1965332031
506.4204407 354.5626525879
532.6748657 764.1384277344
571.065918 2295.6982421875
571.2571411 1163.8527832031
571.3283081 242.7926635742
572.0714111 1137.6363525391
572.3601074 262.6578369141
649.9946289 431.6261901855
保存为"test.mgf"
运行以下代码
import matplotlib.pyplot as plt
def read_mgf(file_path):
with open(file_path, 'r') as file:
spectra = []
spectrum = {}
mz_list = []
intensity_list = []
for line in file:
line = line.strip()
if line == "BEGIN IONS":
spectrum = {}
mz_list = []
intensity_list = []
elif line == "END IONS":
spectrum['mz'] = mz_list
spectrum['intensity'] = intensity_list
spectra.append(spectrum)
elif '=' in line:
key, value = line.split('=', 1)
spectrum[key] = value
else:
if line:
mz, intensity = line.split()
mz_list.append(float(mz))
intensity_list.append(float(intensity))
return spectra
def plot_spectrum(spectrum):
"""
可视化质谱图
"""
mz = spectrum['mz']
intensity = spectrum['intensity']
plt.figure(figsize=(10, 5))
plt.stem(mz, intensity, linefmt='b-', markerfmt=' ', basefmt=' ')
plt.title(spectrum.get('TITLE', 'Mass Spectrum'))
plt.xlabel('m/z')
plt.ylabel('Intensity')
plt.grid(True)
plt.show()
# 使用示例
file_path = 'test.mgf' # 替换为你的 .mgf 文件路径
spectra = read_mgf(file_path)
if spectra:
# 可视化第一张图谱
first_spectrum = spectra[0]
plot_spectrum(first_spectrum)
else:
print("No spectra found in the file.")
image.png