2016-11-02 2 views
0

私はからファイルdisp.txtを変換しようとしているこんにちは:disp.molするPythonでテキストファイルのN行上interateする方法

116 C    0.12 -0.91 0.39 -0.40 0.31 0.85 -0.66 -0.18 -0.22 
117 O    0.00 -0.02 0.00 -0.05 0.05 0.12 -0.57 -0.26 -0.29 
116 C   -0.03 -0.04 0.00  0.01 0.09 0.19 -0.71 -0.21 -0.26 
117 O   -0.14 0.88 -0.45  0.47 -0.33 -0.79  0.57 0.16 0.19 

vibration 1 
0.12 -0.91 0.39 
0.0 -0.02 0.0 
vibration 2 
-0.4 0.31 0.85 
-0.05 0.05 0.12 
vibration 3 
-0.66 -0.18 -0.22 
-0.57 -0.26 -0.29 
vibration 4 
-0.03 -0.04 0.00 
-0.14 0.88 -0.45 
vibration 5 ... 

lines = f.readlines()を使用して行を読み込みます。

このファイルを開くと、disp.txtファイルが開かれています(disp.txt、w)。 vib1 = []でそれらを数= x.split()

次いでvib1.append(フロート(番号[2]))、vib2.appendと格納された、:

は行中のXに使用してデータを分割しましたvib2 = []など

私がdisp.molの形式で保存したデータを置く必要があるときに、私の問題が発生します。下のコードでは、最初の2つの線から最初の3つの振動の出力を得ることができますが、次の2つの2つの線で同じループを実行する方法がわかりません(さらに2Nの線があれば) 。私はまた、各振動に番号を付ける方法もわかりません。これについての助けに感謝します。

with open('disp.mol', 'w') as thisfile: 
     thisfile.writelines('vibration') 
     thisfile.writelines('\n') 
     for x in range (0, 2): 
       vib_one = str(vib1[x]) + ' ' + str(vib2[x]) + ' ' + str(vib3[x]) 
       thisfile.writelines(vib_one) 
       thisfile.writelines('\n') 
     thisfile.writelines('vibration') 
     thisfile.writelines('\n') 
     for x in range (0, 2): 
       vib_two = str(vib4[x]) + ' ' + str(vib5[x]) + ' ' + str(vib6[x]) 
       thisfile.writelines(vib_two) 
       thisfile.writelines('\n') 
     thisfile.writelines('vibration') 
     thisfile.writelines('\n') 
     for x in range (0, 2): 
       vib_three = str(vib7[x]) + ' ' + str(vib8[x]) + ' ' + str(vib9[x]) 
       thisfile.writelines(vib_three) 
       thisfile.writelines('\n') 

出力:

vibration 
0.12 -0.91 0.39 
0.0 -0.02 0.0 
vibration 
-0.4 0.31 0.85 
-0.05 0.05 0.12 
vibration 
-0.66 -0.18 -0.22 
-0.57 -0.26 -0.29 

答えて

0

は、ここでそれを行う方法です:

with open('disp.txt') as f, open('disp.mol','w') as out: 
    vibration = 1 
    for line in f: 
     line1 = line.split() 
     line2 = next(f).split() # also get next line 
     for i in range(2,len(line1),3): 
      out.write('vibration {}\n'.format(vibration)) 
      out.write(' '.join(line1[i:i+3])+'\n') 
      out.write(' '.join(line2[i:i+3])+'\n') 
      vibration += 1 

出力:

vibration 1 
0.12 -0.91 0.39 
0.00 -0.02 0.00 
vibration 2 
-0.40 0.31 0.85 
-0.05 0.05 0.12 
vibration 3 
-0.66 -0.18 -0.22 
-0.57 -0.26 -0.29 
vibration 4 
-0.03 -0.04 0.00 
-0.14 0.88 -0.45 
vibration 5 
0.01 0.09 0.19 
0.47 -0.33 -0.79 
vibration 6 
-0.71 -0.21 -0.26 
0.57 0.16 0.19 
+0

これがうまく働いたありがとうございました。私はあなたの解決策でnext(f).split()の意味にちょっと固執しました。しかし、今私はそれをもっとよく理解していると思う。 – Tillie

+0

@Tillie 'f'は入力ファイルイテレータです。 'next(f)'は直ちに別の行を読み込み、そのたびに2行が 'for'ループで読み込まれます。 'split()'は、空白の行をリストに分割するだけです。 –

関連する問題