2017-04-05 10 views
0

デフォルトでは、私のpythonスクリプトはstdinからデータを取り出し、stdoutに書き出します。しかし、特定のコマンドラインオプションを指定すると、ファイルから読み込んだり、ファイルに書き込んだりすることができます。Python:数字の列の可変数を読み取る

このスクリプトでは、2つの数字の列が読み込まれ、タブとスペースで区切られています。 2つ以上の数値の列を読み込むようにする必要があります(私は他のスクリプトを使って、これらの出力を別のスクリプトの入力にパイプします)。

def main(argv): 
    fin=sys.stdin 
    fout=sys.stdout 
    w=3 
    plot=False 
    graph=False 
    ifile="stdin" 
    ofile="stdout" 
    filt="Median" 
    ydata=False 
    try: 
     opts, args=getopt.getopt(argv,"hi:o:w:ps:qf:y",["ifile=","ofile="]) 
    except getopt.GetoptError: 
    print sys.argv[0] + ' [-i <inputfile>] [-o <outputfile>] [-w <int>] [-p] [-s <imagefile>] [-q] [-f <int>] [-y]' 
    sys,exit(1) 
    for opt, arg in opts: 
    if opt=='-h': 
     print sys.argv[0] + ' [-i <inputfile>] [-o <outputfile>] [-w <int>] [-p] [-s <imagefile>] [-q] [-f <int>] [-y]n' 
     print ' -w filter window size (default=3)' 
     print ' -p display plot' 
     print ' -s save plot as imagefile (eps, jpeg, jpg, pdf, pgf, png, ps, raw, rgba, svg, svgz, tif, tiff)' 
     print ' -i if no inputfile is specified, read from STDIN' 
     print ' -o if no outputfile is specified, print to STDOUT' 
     print ' -f integer: 1=median (default), 2=moving average, 3=Wiener' 
     print ' -q quiet; suppress output' 
     print ' -y include y-data in output' 
     sys.exit() 
    elif opt in ("-i", "--ifile"): 
     ifile=arg 
    elif opt in ("-o", "--ofile"): 
     ofile=arg 
    elif opt in ("-q"): 
     ofile="/dev/null" 
    elif opt in ("-w"): 
     w=int(arg) 
    elif opt in ("-p"): 
     plot=True 
    elif opt in ("-f"): 
     if int(arg)==2: 
     filt="Moving Average" 
     elif int(arg)==1: 
     filt="Median" 
     elif int(arg)==3: 
     filt="Wiener" 
    elif opt in ("-s"): 
     graph=True 
     imagefile=arg 
    elif opt in ("-y"): 
     ydata=True 

    fin=open(ifile,'r') 
    lines=fin.readlines() 
    fin.close() 

# Initialize two lists 
    xl = [] 
    y1l = [] 

    for line in lines: 
     p = line.split() 
     xl.append(float(p[0])) 
     y1l.append(float(p[1])) 

# Convert the lists to arrays 
    x = np.array(xl) 
    y1 = np.array(y1l) 

    if filt=="Median": 
    yf=median(y1,width=w) 
    elif filt=="Moving Average": 
    yf=movingaverage(y1,w) 
    elif filt=="Wiener": 
    yf=wiener(y1,mysize=w) 

    fout=open(ofile,'w') 
    if ydata: 
    outdata=np.array([x,y1,yf]) 
    fmt=['%4.1f','%13.5e','%13.5e'] 
    else: 
    outdata=np.array([x,yf]) 
    fmt=['%4.1f','%13.5e'] 
    outdata=outdata.T 
    np.savetxt(fout, outdata, fmt) 
    fout.close() 

最初の列がXLと呼ばれるリストに格納され、その後、Xと呼ばれる配列に変換される:ここ

は、私が持っているものです。

第2列はy1lというリストに格納され、y1という配列に変換されます。

3番目の列がある場合は、y2lという名前のリストに格納され、次にy2という配列に変換されます。

など。

そして、列の数は変数に格納する必要があります。

多分、すべての入力データを多次元リストに格納してから配列する方がよいでしょうか?私は実際にはリストを必要としません。それらは、データを配列に取得するための中間ステップでのみ使用されます。リスト内のデータをスキップして直接配列に格納することが可能な場合は、それが良いでしょう。

+0

再現性のために、* movingaverage *、* median *、* weiner *などの定義されたメソッドを含めるようにしてください。そして2つ後の可変列はどのように計算されるべきですか?中央値/移動平均/全配列のウェイナー?最初の列、* xl *はインジケータフィールドですか? – Parfait

+0

機能は無関係です。彼らは私が尋ねた質問とは関係がありません。あなたは何かを作ることができます。 デフ中央値(X、W): リターンX デフ移動平均(X、W): リターンX デフウインナー(X、W):X 輸入がある リターン: import sys、getopt matplotlib.pyplotをpltとしてインポート numpyをnpとしてインポート – Mannix

答えて

0

numpy.loadtxtを使用して、ネストされたリストを持つforのループを回避して、すべての列でテキストファイルを直接ロードすることを検討してください。その後、必要に応じて、列全体で機能を実行するにはnumpy.apply_along_axisを使用します。

mat = np.loadtxt(ifile, delimiter="\t") 

if filt=="Median": 
    output_mat = np.apply_along_axis(median, 0, w) 

elif filt=="Moving Average": 
    output_mat = np.apply_along_axis(movingaverage, 0, w) 

elif filt=="Wiener": 
    output_mat = np.apply_along_axis(weiner, 0, w) 

np.savetxt(ofile, output_mat, delimiter='\t') 
+0

これまでのところ行ってください。 (DAT = np.loadtxt(IF1) plt.plot = "2col.dat" 場合PLT としてNP 輸入matplotlib.pyplotとして インライン '輸入numpyの...私はデータをプロットしたいとします plt.show() ' 2つの列があることが分かっていれば、これは問題ありません。しかし、列が増えれば、どれくらいの数がわからないのでしょうか? 最初の列を 'x'軸、残りを 'y1'、 'y2'、...、 'yn'、および 'n'が不明であるとします。 – Mannix

0

ここで私はそれを思いつきました。

#!/usr/bin/python 

import numpy as np 
import sys 
import os 
import matplotlib.pyplot as plt 
import math 

# set the default input to STDIN 
infile=sys.stdin 

# load the data from input 
data=np.loadtxt(infile) 
rows=len(data) 
cols=len(data[0]) 

# find the minimum and maximum x-values 
xmin=min(data[:,0]) 
xmax=max(data[:,0]) 

# create the plot 
fig=plt.figure() 
fig.set_size_inches(16,9) 
fig.set_dpi(120) 
plt.plot(data[:,0],data[:,1:]) 
plt.ylim(ymin=1e-6) 
plt.xlim(xmin,xmax) 
plt.grid(which='major',linestyle='-',linewidth='0.3') 
plt.xlabel('energy (eV/u)') 
plt.ylabel(r'cross section (10$^{-16}$ cm$^{2}$)') 
plt.xscale('log',basex=10) 
plt.yscale('log',basey=10) 
plt.show() 
関連する問題