2017-02-23 1 views
0

Ich habe einen Spaltenvektor eine Molekülgeometrie im FormatPython: konvertiert eine Spaltenvektor Dateiformat

x1 
y1 
z1 
x2 
y2 
z2 
x3 
y3 
z3 
x4 
y4 
z4 
x5 
y5 
z5 
x6 
y6 
z6 
x7 
y7 
z7 
x8 
y8 
z8 

Ich möchte wandeln diese in ein .xyz Dateiformat .xyz:

number of atoms 
comment line 
C x1 y1 z1 
H x2 y2 z2 
H x3 y3 z3 
C x4 y4 z4 
H x5 y5 z5 
H x6 y6 z6 
O x7 y7 z7 
O x8 y8 z8 

Ist das leicht gemacht? Wenn es schwierig ist, die Atomtypen hinzuzufügen, wäre es einfach, die Koordinaten an die Spalten anzuordnen (zumindest reduziert es die Menge an manueller Arbeit).

Antwort

0

Ich verstehe nicht, was die Buchstaben O, H, C bedeuten oder wie man diese Information hinzufügt (ich bin kein Chemiker). Wo sind sie gespeichert? Aber wenn Sie ein Wissenschaftler sind, verwenden Sie wahrscheinlich das numpige Modul. Also hier ist eine einfache Lösung, um Ihre Zeilen drei von drei transponieren:

import numpy as np 
import csv 

#assuming your vector is in a text file 
vector = np.genfromtxt('yourfilename.txt',dtype='str') 

a = np.array(vector) 
a = a.reshape((-1, 3)) 

print(a) 

Ausgang:

[['x1' 'y1' 'z1'] 
['x2' 'y2' 'z2'] 
['x3' 'y3' 'z3'] 
['x4' 'y4' 'z4'] 
['x5' 'y5' 'z5'] 
['x6' 'y6' 'z6'] 
['x7' 'y7' 'z7'] 
['x8' 'y8' 'z8']] 

""" 
The output is a list of lists in which each element is a row. 
Numpy has a simple method to write a 2D array in a csv file : 
np.savetxt("youfilename.csv", a, delimiter=",") 
but since I get a bug in this moment, I will use a classical method. 
""" 
with open("output.csv", "w") as f: 
    writer = csv.writer(f) 
    writer.writerows(a) 

Ihre CSV-Datei:

x1,y1,z1 

x2,y2,z2 

x3,y3,z3 

x4,y4,z4 

x5,y5,z5 

x6,y6,z6 

x7,y7,z7 

x8,y8,z8 
+0

Nun, ich muss auch eine Textdatei importieren, die enthält die Zahlen (geordnet als Spaltenvektor). Was bedeutet das "\ n"? – Yoda

+0

@Yoda \ n bedeutet "newline", das ist ein Zeichen wie jedes andere. Sie können gelöscht werden. Ich werde meine Antwort bearbeiten und klären. –

Verwandte Themen