[Tutor] building table from textfile
Alan Gauld
alan.gauld at btinternet.com
Thu Nov 28 02:55:17 CET 2013
On 27/11/13 18:22, Ruben Guerrero wrote:
> Dear tutor.
>
> I am trying to build the matrix and get some other information from the
> following text files:
>
> file1:
> -O-
> 1 2 3 4 5 6
> 1 C 6.617775 -0.405794 0.371689 -0.212231 0.064402
> 0.064402
> 2 C -0.405794 6.617775 -0.212231 0.371689 -0.010799
> -0.010799
> 3 C 0.371689 -0.212231 4.887381 -0.005309 0.263318
> 0.263318
> 4 C -0.212231 0.371689 -0.005309 4.887381 -0.005500
> -0.005500
> 7 8 9 10
> 1 C 0.064402 -0.010799 -0.010799 -0.010799
> 2 C -0.010799 0.064402 0.064402 0.064402
> 3 C 0.263318 -0.005500 -0.005500 -0.005500
> 4 C -0.005500 0.263318 0.263318 0.263318
>
> file 2:
> -O-
> 1 2 3 4 5
> 1 C 5.898497 0.292009 0.177195 0.177195 0.177195
> 2 H 0.292009 0.686184 -0.099114 -0.099114 -0.099114
> 3 Cl 0.177195 -0.099114 17.045753 -0.129074 -0.129074
> 4 Cl 0.177195 -0.099114 -0.129074 17.045753 -0.129074
>
> using the following script:
>
> nombreInput=sys.argv[1]
>
> inputFile = open (nombreInput,"r")
> inputFileRead = inputFile.readlines()
> out = open (nombreInput+".out","w")
>
>
> mu = 0
> nu = 0
>
> countAtom = {
...
> }
> electrons = {
...
> }
>
> numberOfLines = len(inputFileRead)
>
> maxNumberOfOrbitals = 0
>
> # Contar el numero de orbitales
> for iline in range(0,numberOfLines) :
> inputFileRead[iline] = inputFileRead[iline].replace("\n","")
You could do this more simply using
for line in inputFile:
line = line.rstrip()
> if ( len(inputFileRead[iline].split()) == 6+2 ) :
> numberOfOrbital = int(inputFileRead[iline].split()[0])
And this becomes
line = line.split()
if len(line) == 8: # 8 = 6+2 no point in extra math
numberOfOrbital = int(line[0])
> if ( numberOfOrbital > maxNumberOfOrbitals ) :
> maxNumberOfOrbitals = numberOfOrbital
> # Contar los atomos
>
> for k in range(0,maxNumberOfOrbitals) :
> atom = inputFileRead[k+2].split()[1]
This assumes you have 2 more lines than there are maxNumberofOrbitals.
I didn't check, but is it true?
Also it would be more efficient to store the split line in the first
loop above.
I didn't go through the rest in detail but I suspect
the +2 thing may be to do with your error message:
> elif ( len(inputFileRead[l].split()) == maxNumberOfOrbitals%6+2 ) :
> for j in range(0,maxNumberOfOrbitals%6) :
> matrix[i][j+6*m] = float (inputFileRead[l].split()[j+2])
Notice the j+2 at the end?
Could that be the cause?
Or what about the j+6*m? I don't know where m is defined but
could it be busting your index?
> Traceback (most recent call last):
> File "get_matrix.py", line 88, in <module>
> matrix[i][j+6*m] = float (inputFileRead[l].split()[j+2])
> IndexError: index 10 is out of bounds for axis 0 with size 10
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.flickr.com/photos/alangauldphotos
More information about the Tutor
mailing list