Pythonでcsv読み込み&書き込み(クラスに分割ver)
Pythonのクラスの書き方に手を出す。オブジェクト指向は Java を挫折してから苦手意識があるが…
とりあえず、以前つくった『Pythonでcsv読み込み&書き込み』をクラスを使って書きなおしてみた。
greenhornprofessional.hatenablog.com
プログラム
メインのpyファイル
# 17_ReadWriteCsv_001.py # python 3.8.1 # coding: utf-8 # import csv import datetime import _17_procClass_001 as pc def main(): now = datetime.datetime.now() fi = '17_peak.csv' fo = '17_peakResult_{0:%Y%m%d%H%M%S}.csv'.format(now) with open(fi, mode='r', newline='') as f_in: reader = csv.reader(f_in) data_array = [row for row in reader] arry_x = [] arry_y = [] for i in data_array: arry_x.append(float(i[0])) arry_y.append(float(i[1])) instance = pc.ProcClass(arry_x, arry_y) print("----Start-----") result = instance.splineInterpolation() print("----End-------") with open(fo, mode='a') as f_out: csvWriter = csv.writer(f_out, lineterminator = '\n') csvWriter.writerows(result) if __name__ == '__main__': main()
クラスのpyファイル ※メインのpyファイルと同じ階層に置いている
# _17_procClass_001.py # python 3.8.1 # coding: utf-8 # import numpy as np from scipy import signal, interpolate from matplotlib import pylab as plt class ProcClass: arry_x, arry_y = [], [] def __init__(self, x, y): print("--Initialized--") self.arry_x = x self.arry_y = y def splineInterpolation(self): x_min = min(self.arry_x) x_max = max(self.arry_x) t = np.linspace(x_min, x_max, 100) f = interpolate.interp1d(self.arry_x, self.arry_y, kind="quadratic") y = f(t) splineArry = np.array([t, y]) splineArry_t = splineArry.T print("Please close the figure1 to continue.") plt.plot(self.arry_x, self.arry_y,"r") plt.plot(t, y) plt.show() return splineArry_t