48行报错:发生异常: NameError name 'perform_tsa_transform' is not defined File "/Users/dingfengyan/工作/项目开发/哈理工/批量导出功能/feature.py", line 48, in process_csv_files perform_tsa_transform(file_path, tsa_window_size) ^^^^^^^^^^^^^^^^^^^^^ File "/Users/dingfengyan/工作/项目开发/哈理工/批量导出功能/feature.py", line 52, in <module> process_csv_files(currentPath, 1000) NameError: name 'perform_tsa_transform' is not defined
时间: 2023-08-05 10:03:07 浏览: 129
testusb.rar_Linux/Unix编程_Unix_Linux_
抱歉,我之前的回答中有一个错误。在代码中,我错误地将 `perform_tsa_transform` 函数放在了 `extract_and_convert_zip_files` 函数内部的代码块中,导致无法在 `process_csv_files` 函数中调用该函数。
以下是修改后的代码,已修复此问题:
```python
import os
import csv
import struct
import zipfile
def extract_and_convert_zip_files(folder_path, output_folder):
for root, dirs, files in os.walk(folder_path):
for file in files:
if file.endswith(".zip"):
file_path = os.path.join(root, file)
extract_zip_files(file_path, output_folder)
def extract_zip_files(file_path, output_folder):
with zipfile.ZipFile(file_path, "r") as zip_file:
for file_info in zip_file.infolist():
if file_info.filename.endswith(".bin"):
bin_data = zip_file.read(file_info.filename)
output_file_name = os.path.splitext(file_info.filename)[0] + "_original.csv"
output_file_path = os.path.join(output_folder, output_file_name)
convert_binary_to_csv(bin_data, output_file_path)
perform_tsa_transform(output_file_path)
def convert_binary_to_csv(bin_data, output_file_path):
with open(output_file_path, "w", newline="") as csv_file:
csv_writer = csv.writer(csv_file)
csv_writer.writerow(["Column 1", "Column 2", "Column 3"])
pos = 0
while pos < len(bin_data):
binary_data = bin_data[pos:pos+8]
pos += 8
float_data = struct.unpack("fff", binary_data)
csv_writer.writerow(float_data)
def perform_tsa_transform(input_csv_file):
window_size = 3 # 设置TSA的窗口大小
output_csv_file = input_csv_file.replace("_original.csv", "_tsa.csv")
with open(input_csv_file, "r") as input_file, open(output_csv_file, "w", newline="") as output_file:
csv_reader = csv.reader(input_file)
csv_writer = csv.writer(output_file)
csv_writer.writerow(["Column 1", "Column 2", "Column 3"])
data_columns = [1, 2, 3] # 指定需要进行TSA处理的列
data = [[] for _ in data_columns]
for row in csv_reader:
for i, col in enumerate(data_columns):
data[i].append(float(row[col]))
if len(data[0]) == window_size:
transformed_data = perform_tsa_transform_window(data)
csv_writer.writerow(transformed_data)
for i in range(len(data)):
data[i].pop(0)
def perform_tsa_transform_window(data):
transformed_data = []
for i in range(len(data[0])):
window_data = [data[j][i] for j in range(len(data))]
transformed_data.append(sum(window_data) / len(window_data))
return transformed_data
# 指定文件夹路径和输出文件夹路径进行调用
extract_and_convert_zip_files("your_folder_path", "your_output_folder_path")
```
请确保 `perform_tsa_transform` 函数位于 `extract_and_convert_zip_files` 函数之外,并在 `process_csv_files` 函数中调用 `perform_tsa_transform` 函数。
如果您仍然遇到问题,请检查代码中是否存在其他错误,并确保所有函数都在正确的位置定义和调用。
阅读全文