高级玩家

- 贡献度
- 0
- 金元
- 2715
- 积分
- 272
- 精华
- 0
- 注册时间
- 2011-2-14
|
v#!usrbinenv python# -- codingutf-8 --
import os
import pandas as pd
import matplotlib.pyplot as plt
from scipy.signal import welch
from matplotlib import rcParams
import matplotlib
import numpy as np
from docx import Document
from docx.shared import Cm,Pt
import math
from docx.enum.text import WD_ALIGN_PARAGRAPH
matplotlib.use('TkAgg')
import matplotlib
matplotlib.use('TkAgg')
def process_txt_files(directory)
for filename in os.listdir(directory)
if filename.endswith(dat.txt)
plotname_1 = os.path.splitext(os.path.basename(filename))[0]
plotname = os.path.splitext(os.path.basename(plotname_1))[0]
plotname_plot = plotname+.plot
plotname_plot_path = os.path.join(directory, plotname_plot)
if os.path.exists(plotname_plot_path)
print(f跳过{plotname_plot_path}文件已存在)
continue
filepath = os.path.join(directory,filename)
process_file(filepath)
def process_file(file_path)
# 构造完整的输入文件路径和输出文件路径
# 尝试读取文件
try
df = pd.read_csv(file_path, sep='s+', header=0, encoding='GBK', low_memory=False)
except UnicodeDecodeError
# 如果GBK编码失败,则尝试使用UTF-8编码读取
try
df = pd.read_csv(file_path, sep='s+', header=0, encoding='UTF-8', low_memory=False)
except UnicodeDecodeError
# 如果UTF-8也失败,则打印错误消息并返回
print(fError reading file {file_path} Unable to decode with GBK or UTF-8.)
return
# 剔除第4列值不是“0x210a”的行
df = df[df.iloc[, 3] == '0x210a']
# 仅保留第3、7、8、9、10、11、12列的数据
df_filtered = df.iloc[, [2, 6, 7, 8, 9, 10, 11]]
# 保存剩余数据到新的文本文件中
# 构建新的文件名
new_filename_1 = os.path.splitext(os.path.basename(file_path))[0]
new_filename_2 = os.path.splitext(os.path.basename(new_filename_1))[0]
new_filename=new_filename_2+.plot.txt
new_filepath = os.path.join(os.path.dirname(file_path), new_filename)
try
df_filtered.to_csv(new_filepath, sep='t', index=False, header=False)
print(f处理完成,结果已保存到 {new_filepath})
except Exception as e
print(f保存文件 {new_filepath} 时发生错误:{e})
def process_doc_files(directory)
for filename in os.listdir(directory)
if filename.endswith(.plot.txt)
filepath = os.path.join(directory, filename)
plotname_1 = os.path.splitext(os.path.basename(filename))[0]
plotname = os.path.splitext(os.path.basename(plotname_1))[0]
plotname_doc=plotname+.docx
plotname_doc_path=os.path.join(directory,plotname_doc)
if os.path.exists(plotname_doc_path)
print(f跳过{plotname_doc_path}文件已存在)
continue
plot_and_save_to_docx(filepath,directory,plotname)
def plot_and_save_to_docx(file_path,directory,plotname)
# 读取数据
df = pd.read_csv(file_path, sep='t', header=None)
rcParams['font.sans-serif'] = ['Microsoft YaHei']
rcParams['axes.unicode_minus'] = False
# 提取列数据
x = df.iloc[, 0]
y1 = df.iloc[, 14]
y2 = df.iloc[, 47]
#定义颜色列表,为每个方向分配一种颜色
colors = ['red', 'green', 'blue']
directions = ['X', 'Y', 'Z']
# 绘制1加速度时域图
fig1, ax1 = plt.subplots(figsize=(10, 6))
for i, col in enumerate(y1.columns)
ax1.plot(x, y1[col], label=f'{directions}方向加速度', color=colors, alpha=0.6)
ax1.legend()
ax1.set_title('三方向加速度时域图 (X, Y, Z)'+f-{plotname})
ax1.set_xlabel('时间 (s)')
ax1.set_ylabel('加速度 (g)')
ax1.grid(True,color=gray,linestyle=--,linewidth=0.5)
plt.tight_layout()
plt.savefig('temp_acc.png')
plt.close(fig1)
# 绘制2角速度时域图
fig2, ax2 = plt.subplots(figsize=(10, 6))
for i, col in enumerate(y2.columns)
ax2.plot(x, y2[col], label=f'{directions}方向角速度', color=colors, alpha=0.6)
ax2.legend()
ax2.set_title('三方向角速度时域图 (X, Y, Z)'+f-{plotname})
ax2.set_xlabel('时间 (s)')
ax2.set_ylabel('角速度 (rads)')
ax2.grid(True,color=gray,linestyle=--,linewidth=0.5)
plt.tight_layout()
plt.savefig('temp_vel.png')
plt.close(fig2)
# 计算3并绘制加速度功率谱密度图及RMS
fs = 1000 # 采样频率
fig3, ax3 = plt.subplots(figsize=(10, 6))
rms1 = []
for i, col in enumerate(y1.columns)
f, Pxx = welch(y1[col], fs, nperseg=len(y1[col]))
ax3.plot(f, Pxx, label=f'{directions}方向加速度', color=colors, alpha=0.6)
rms1.append(math.sqrt(np.mean(y1[col] 2)))
ax3.set_yscale('log')
ax3.legend()
# 展示每个方向的RMS值
for i, rms_val in enumerate(rms1)
ax3.text(0.05, 0.9 - 0.05 i, f'{directions}方向 RMS {rms_val.2f}', transform=ax3.transAxes)
ax3.set_title('三方向加速度功率谱密度曲线 (X, Y, Z)'+f-{plotname})
ax3.set_xlabel('频率 (Hz)')
ax3.set_ylabel('功率谱密度 (g^2Hz)')
ax3.grid(True,color=gray,linestyle=--,linewidth=0.5)
plt.tight_layout()
plt.savefig('temp_acc_psd.png')
plt.close(fig3)
# 计算4并绘制角速度功率谱密度图及RMS
fig4, ax4 = plt.subplots(figsize=(10, 6))
rms2 = []
for i, col in enumerate(y2.columns)
f, Pxx = welch(y2[col], fs, nperseg=len(y2[col]))
ax4.plot(f, Pxx, label=f'{directions}方向角速度', color=colors, alpha=0.6)
rms2.append(math.sqrt(np.mean(y2[col] 2)))
ax4.set_yscale('log')
ax4.legend()
# 展示每个方向的RMS值
for i, rms_val in enumerate(rms2)
ax4.text(0.05, 0.9 - 0.05 i, f'{directions}方向 RMS {rms_val.2f}', transform=ax4.transAxes)
ax4.set_title('三方向角速度功率谱密度曲线 (X, Y, Z)'+f-{plotname})
ax4.set_xlabel('频率 (Hz)')
ax4.set_ylabel('功率谱密度 ((rads)^2Hz)')
ax4.grid(True,color=gray,linestyle=--,linewidth=0.5)
plt.tight_layout()
plt.savefig('temp_vel_psd.png')
plt.close(fig4)
#RMSDOC
RMS_filename = directory+rRMS.docx
if os.path.exists(RMS_filename)
doc=Document(RMS_filename)
table=doc.tables[-1]
else
doc=Document()
table = doc.add_table(rows=1, cols=7)
table.alignment=WD_ALIGN_PARAGRAPH.CENTER
hdr_cells = table.rows[0].cells
hdr_cells[0].text = 测试条件
hdr_cells[1].text = X向加速度RMS
hdr_cells[2].text = Y向加速度RMS
hdr_cells[3].text = Z向加速度RMS
hdr_cells[4].text = X向角速度RMS
hdr_cells[5].text = Y向角速度RMS
hdr_cells[6].text = Z向角速度RMS
# 添加数据
row_cells = table.add_row().cells
row_cells[0].text = plotname
for i in range(3)
row_cells[i + 1].text = f{rms1.3f}
row_cells[i + 4].text = f{rms2.3f}
doc.save(RMS_filename)
# 创建Word文档
filename_without_path = os.path.splitext(os.path.basename(file_path))[0] + '.docx'
docx_filename = os.path.join(directory, filename_without_path)
if not os.path.exists(docx_filename)
doc = Document()
# 添加一个标题,并设置其居中
heading = doc.add_heading('数据分析报告'+f-{plotname}, level=1)
heading.alignment = WD_ALIGN_PARAGRAPH.CENTER
heading.runs[0].font.size = Pt(14)
# 添加时域图
doc.add_heading('三方向加速度(时域)', level=2)
doc.add_picture('temp_acc.png', width=Cm(7))
doc.add_heading('三方向角速度(时域)', level=2)
doc.add_picture('temp_vel.png', width=Cm(7))
# 添加PSD图
doc.add_heading('三方向加速度功率谱密度曲线', level=2)
doc.add_picture('temp_acc_psd.png', width=Cm(7))
doc.add_heading('三方向角速度功率谱密度曲线', level=2)
doc.add_picture('temp_vel_psd.png', width=Cm(7))
# 保存文档
doc.save(docx_filename)
print(f'报告已保存到 {docx_filename}')
# 删除临时图片
for temp_file in ['temp_acc.png', 'temp_vel.png', 'temp_acc_psd.png', 'temp_vel_psd.png']
if os.path.exists(temp_file)
os.remove(temp_file)
# 调用函数处理目录中的文件
process_txt_files(r'Gwork2Z2hziazhenyan20242024-zhai-shiyan20241101save')
process_doc_files(r'Gwork2Z2hziazhenyan20242024-zhai-shiyan20241101save')
|
|