2013-11-27 2 views
0

불쌍한 Engish를 유감스럽게 생각합니다. 반복되는 형식의 파일이 있습니다. 이러한Python : 복잡하고 형식을 바꾸는 형식의 파일을 읽고 쓰십시오.

 326           Iteration:  0 #Bonds:  10 
    1 6 7 14 54 70 77 0 0 0 0 0 1 0.693 0.632 0.847 0.750 0.644 0.000 0.000 0.000 0.000 0.000 3.566 0.000 0.028 
    2 6 3 6 15 55 0 0 0 0 0 0 1 0.925 0.920 0.909 0.892 0.000 0.000 0.000 0.000 0.000 0.000 3.645 0.000 -0.040 
    3 6 2 8 10 52 0 0 0 0 0 0 1 0.925 0.910 0.920 0.898 0.000 0.000 0.000 0.000 0.000 0.000 3.653 0.000 0.000 
... 
    324 8 323 0 0 0 0 0 0 0 0 0 100 0.871 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.871 3.000 -0.493 
    325 2 326 0 0 0 0 0 0 0 0 0 101 0.930 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.930 0.000 0.334 
    326 8 325 0 0 0 0 0 0 0 0 0 101 0.930 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.930 3.000 -0.611 
    637.916060425841  306.094529423257  1250.10511927236 
    6.782126993565285E-006 
     326 (repeating from here)     Iteration:  100 #Bonds:  10 
    1 6 7 14 54 64 70 77 0 0 0 0 1 0.885 0.580 0.819 0.335 0.784 0.709 0.000 0.000 0.000 0.000 4.111 0.000 0.025 
    2 6 3 6 15 55 0 0 0 0 0 0 1 0.812 0.992 0.869 0.966 0.000 0.000 0.000 0.000 0.000 0.000 3.639 0.000 -0.034 
    3 6 2 8 10 52 0 0 0 0 0 0 1 0.812 0.966 0.989 0.926 0.000 0.000 0.000 0.000 0.000 0.000 3.692 0.000 0.004 
  • 당신이 여기에서 볼 수 있듯이으로 '첫 번째 줄은 헤더이고, 둘째는 ~ 327 라인은 내가 분석 할 데이터이며, 328번째과 329 라인은 내가 돈 몇 가지 숫자를 가지고 사용하고 싶지 않다. 다음 "프레임"은 정확히 같은 형식으로 330 행에서 시작합니다. 이 "프레임"은 200000 번 이상 반복됩니다.
  • 각 프레임의 2 ~ 327 번째 라인 데이터에서 1 ~ 13 번째 열을 사용하고 싶습니다. 또한 머리글의 첫 번째 번호를 사용하고 싶습니다.
  • 모든 반복되는 "프레임"의 각 2 ~ 327 번째 줄의 3 ~ 12 번째 열, 각 프레임의 대상 행렬에서 인쇄 번호 0과 0이 아닌 데이터의 수를 분석하고 싶습니다. 또한 1, 2 및 13 열을 인쇄하십시오. 첫 번째 줄의 첫 번째 번호 : 그래서 예상되는 출력 파일

    326 
        1 
    1 6 5 5 1 
    2 6 4 6 1 
    ... 
    325 2 1 9 101 
    326 8 1 9 101 
    326 (Next frame starts from here) 
        2 
    1 6 5 5 1 
    2 6 4 6 1 
    ... 
    326 
        3 
    1 6 5 5 1 
    2 6 4 6 1 
    ... 
    
  • 첫 번째 줄과 같이된다.
  • 두 번째 줄 : 프레임 번호
  • 3 ~ 328 번째 줄 : 입력 파일의 첫 번째 열, 입력 파일의 두 번째 열, 입력의 3 번째 ~ 12 번째 열의 0이 아닌 수, 3 번째 ~ 12 번째 열의 0 수 입력 및 13 번째 열에 입력합니다.
  • 4 번째 줄부터 : 반복 형식, 위와 동일.

따라서 결과 파일에는 2 개의 헤더 행이 있고 326 행의 분석 데이터가 각 프레임 당 총 328 행에 있습니다. 동일한 형식이 다음 프레임에도 반복됩니다. 결과 데이터 형식 (각 5 공백)을 사용하여 다른 용도로 파일을 사용하는 것이 좋습니다.

내가 사용하는 방법은 13 개의 열에 대해 13 개의 배열 만들기 -> 각 프레임 및 각 328 개의 줄에 대해 double for 루프를 사용하여 데이터를 저장하는 것입니다. 그러나 출력에 어떻게 대처할 수 있을지 전혀 알지 못합니다.

다음은 내 시험 코드 (미완성, 입력 읽기 전용)이지만이 코드에는 많은 문제가 있습니다. 라인 캐시는 모든 첫 번째 라인의 첫 번째 숫자가 아니라 전체 라인을 읽습니다. 모든 프레임은 326 + 3 = 329 라인을 가지고 있지만 프레임 워킹을 위해 제 코드가 제대로 작동하지 않는 것 같습니다. 나는 어떤 도움을 환영하고이 자료를 분석하는 것을 돕는다. 대단히 감사드립니다.

# Read the file 
filename = raw_input("Enter the file name \n") 
file = open(filename, 'r') 

# Read the number of atom from header 
import linecache 
nnn = linecache.getline(filename, 1) 
natoms = int(nnn) 
singleframe = natoms + 3 

# get number of frames 
nlines = 0 
for i1 in file: 
    nlines = nlines +1 
file.close() 

nframes = nlines/singleframe 

print 'no of lines are: ', nlines 
print 'no of frames are: ', nframes 
print 'no of atoms are:', natoms 

# Create 1d string array 
nrange = range(nlines) 
data_lines = [None]*(nlines) 

# Store whole input file into string array 
file = open(filename, 'r') 
i1=0 
for i1 in nrange: 
    data_lines[i1] = file.readline() 
file.close() 


# Create 1d array to store atomic data 
at_index = [None]*natoms 
at_type = [None]*natoms 
n1 = [None]*natoms 
n2 = [None]*natoms 
n3 = [None]*natoms 
n4 = [None]*natoms 
n5 = [None]*natoms 
n6 = [None]*natoms 
n7 = [None]*natoms 
n8 = [None]*natoms 
n9 = [None]*natoms 
n10 = [None]*natoms 
molnr = [None]*natoms 

nrange1= range(natoms) 
nframe = range(nframes) 

file = open('output_force','w') 
print data_lines[9] 
for j1 in nframe: 
    start = j1*(natoms + 3) + 3 
    for i1 in nrange1: 
     line = data_lines[i1+start].split() #Split each line based on spaces 
     at_index[i1] = int(line[0]) 
     at_type[i1] = int(line[1]) 
     n1[i1]= int(line[2]) 
     n2[i1]= int(line[3]) 
     n3[i1]= int(line[4]) 
     n4[i1]= int(line[5]) 
     n5[i1]= int(line[6]) 
     n6[i1]= int(line[7]) 
     n7[i1]= int(line[8]) 
     n8[i1]= int(line[9]) 
     n9[i1]= int(line[10]) 
     n10[i1]= int(line[11]) 
     molnr[i1]= int(line[12]) 

답변

0

csv 파일로 작업 할 때 csv module을 조사해야합니다. 트릭을해야하는 코드를 작성했습니다.

이 코드는 "좋은 데이터"라고 가정합니다. 데이터 세트에 오류 (예 : 13보다 적은 열 또는 326보다 적은 데이터 행)가 포함될 수있는 경우 일부 변경을 수행해야합니다.

이 수율 처음 세 라인 용

import csv 
with open('mydata.csv') as in_file: 
    with open('outfile.csv', 'wb') as out_file: 
     csv_reader = csv.reader(in_file, delimiter=' ', skipinitialspace=True) 
     csv_writer = csv.writer(out_file, delimiter = '\t') 

     # Iterate over all rows in the file 
     for i, header in enumerate(csv_reader): 
      # Get the header data 
      num = header[0] 
      csv_writer.writerow([num]) 

      # Write frame number, starting with 1 (hence the +1 part) 
      csv_writer.writerow([i+1]) 

      # Iterate over all data rows 
      for _ in xrange(326): 

       # Call next(csv_reader) to get the next row 
       # Put inside a try ... except to avoid StopIteration exception 
       # if end of file is found before reaching 326 lines 
       try: 
        row = next(csv_reader) 
       except StopIteration: 
        break 
       # Use list comprehension to extract number of zeros 
       zeros = sum([1 for x in row[2:12] if x.strip() == '0']) 
       not_zeros = 10 - zeros 
       # Write the data to output file 
       out = [row[0].strip(), row[1].strip(),not_zeros, zeros, row[12].strip()] 
       csv_writer.writerow(out) 
      # If the 
      else: 
       # Skip the last two lines of the file 
       next(csv_reader) 
       next(csv_reader) 

(파이썬 2.6.6 준수하도록 변경)

326 
1 
1 6 5 5 1 
2 6 4 6 1 
3 6 4 6 1 
+0

감사. 나는 csv 모듈이 있는지조차 몰랐다. 훌륭합니다. 고맙습니다. 입력 파일은 csv 파일이 아니지만 fortran 저작물에서 만들어 지므로 모든 형식이 동일합니다. 에로스에 대해 걱정할 필요가 없습니다. THanks – exsonic01

+0

두 번째 줄은 쉼표로 구문 오류를 나타냅니다. 이걸 어떻게 피할 수 있니? 이것은 아주 기본적인 질문이지만, 용서해주십시오. 전에 이런 모듈을 사용한 적이 없습니다. – exsonic01

+0

어떤 버전의 파이썬을 사용하고 있습니까? (콘솔에'import sys; sys.version'라고 쓰면 콘솔에 표시됩니다.) –

관련 문제