2017-04-05 3 views
0

기본적으로 Python 스크립트는 stdin에서 데이터를 가져 와서 표준 출력에 씁니다. 그러나 특정 명령 행 옵션을 지정하면 파일에서 읽거나 파일에 쓸 수 있습니다.Python : 숫자의 가변 개수의 열 읽기

스크립트는 탭 및/또는 공백으로 구분 된 두 개의 숫자 열만 읽습니다. 두 개 이상의 숫자 열을 읽을 수 있어야합니다 (다른 스크립트를 사용하여이 중 하나의 출력을 다른 입력으로 파이프 할 수 있습니다).

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라는 배열로 변환한다 : 여기서

제가 가지고있는 것이다.

두 번째 열은 y1l이라는 목록에 저장되고 y1이라는 배열로 변환됩니다.

세 번째 열이 있으면 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

중첩 목록이있는 for 루프를 피하기 위해 numpy.loadtxt을 사용하여 모든 열과 함께 텍스트 파일을 직접로드하는 것이 좋습니다. 그런 다음 필요한 경우 열에서 함수를 실행하려면 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

지금까지 간다. PLT로 NP 수입 matplotlib.pyplot으로 내가 데이터를 플롯한다고 가정 ... 인라인'수입 NumPy와 경우 "2col.dat"= DAT = np.loadtxt (IF1) plt.plot (dat [:, 0], dat [:, 1]) plt.show()' 두 개의 열이있는 것이면 괜찮습니다. 그러나 더 많은 기둥이 있고, 얼마나 많이 있는지 모르겠습니까? 첫 번째 열을 '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() 
관련 문제