Foros del Web » Programando para Internet » Python »

SyntaxError: invalid syntax programa InterpText.py

Estas en el tema de SyntaxError: invalid syntax programa InterpText.py en el foro de Python en Foros del Web. Saludos a todos. Ante todo me presento como TUDz, nuevo en esta comunidad. He estado trabajando con un proyecto de procesado sísmico (parte de mi ...
  #1 (permalink)  
Antiguo 28/09/2012, 02:18
 
Fecha de Ingreso: septiembre-2012
Ubicación: Tu corázon
Mensajes: 3
Antigüedad: 11 años, 6 meses
Puntos: 0
Pregunta SyntaxError: invalid syntax programa InterpText.py

Saludos a todos. Ante todo me presento como TUDz, nuevo en esta comunidad.

He estado trabajando con un proyecto de procesado sísmico (parte de mi carrera) y me he empezado a meter en esto de Python. He tenido un serio problema con este codigo que no he podido corregir.

Código python:
Ver original
  1. #!/usr/bin/env python
  2. """
  3. custom code used to build headers for alaska line 31-81.  This hardwires things
  4. like the shot, group, and cdp intervals, number groups and much more.  You may
  5. you is as a guide line to write custom code for other data.  I found the
  6. InterpText class reuseable.
  7.  
  8. usage:
  9. Create input files:
  10. hdrfile.txt output from <line.su sugethw output=geom key=tracl,fldr,tracf
  11. spnElev.txt    Column 1 is the spn.  Column 2 is elevation.  Typed from info in
  12.               surveyors log
  13. recnoSpn.txt   Column 1 is fldr. Column 2 is spn.  fldr is called recno in the
  14.               observers log.  File was typed using info in the observers log
  15.  
  16. The program is run by:
  17. ./InterpText.py > hdrfile1.txt
  18.  
  19. The hdrfile1.txt file is processed using a2b and sushw to load the headers in
  20. file line.su and output allshots.su
  21. """
  22.  
  23. import math
  24.  
  25. class InterpText:
  26.     """
  27.  
  28.    functions to read (xin,yin) pairs and linearly interpolate y(xout)
  29.    xin is assumed to be monotonically increasing
  30.  
  31.    """
  32.  
  33.     def read(self,fileName):
  34.         """
  35.  
  36.        Read pairs from fileName.  Create xin,yin arrays.  xin must be
  37.        monotonically increasing.  There is no validation for two floats
  38.        per line or xin monotopically increasing
  39.  
  40.        """
  41.  
  42.         self.xin=[]
  43.         self.yin=[]
  44.         for self.line in open(fileName):
  45.             tokens=self.line.split()
  46.             self.xin.append(float(tokens[0]))
  47.             self.yin.append(float(tokens[1]))
  48. #        print self.xin
  49. #        print self.yin
  50.     def linearInterp(self,x):
  51.         """
  52.  
  53.        Find smallest such that x is in the interval [xin[i],xin[i+1]]
  54.        Linear interpolate y(x).  Copy first or last yin for values outside
  55.        the range of xin array.
  56.  
  57.        """
  58.  
  59.         if(x<=self.xin[0]):
  60.             return self.yin[0]
  61.         #print "len(self.xin)=" + str(len(self.xin));
  62.         for i in range(0,len(self.xin)-1):
  63.             #print "test x<=self.xin[i+1]" + str(x) + "<=" + str(self.xin[i+1])
  64.             if(x<=self.xin[i+1]):
  65.                 #print "x=" + str(x) + "i=" + str(i)
  66.                 return self.yin[i]+(x-self.xin[i])*                           \
  67.                        (self.yin[i+1]-self.yin[i])/(self.xin[i+1]-self.xin[i])
  68.         return self.yin[len(self.yin)-1]
  69.  
  70. # create InterpText object to interpolate spnElev.txt
  71. spnElev = InterpText()
  72. spnElev.read('spnElev.txt')
  73.  
  74. # create InterpText object to interpolate recnoSpn.txt
  75. recnoSpn = InterpText()
  76. recnoSpn.read('recnoSpn.txt')
  77.  
  78.  
  79. for line in open('hdrfile.txt'):  # read each line in the hdrfile.txt file
  80.     tokens=line.split()
  81.     # get the 3 values on the input record.  (no error checking!!)
  82.     tracl =long(tokens[0])
  83.     fldr  =long(tokens[1])
  84.     tracf =long(tokens[2])
  85.     # set up header values with nulls.
  86.     ep=-999999
  87.     sx    =-999999999
  88.     sy    =-999999999
  89.     gx    =-999999999
  90.     gy    =-999999999
  91.     cdp   =-999999
  92.     sutracf=-999999
  93.     offset=-999999
  94.     shotSpn=-999999999
  95.     gSpn=-999999999
  96.     sdepth=-999
  97.     selev=-999
  98.     gelev=-999
  99.     sstat=-999
  100.     gstat=-999
  101.     tstat=-999
  102.     # compute the shot number corresponding to this fldr (or recno in observer
  103.     # log terminology
  104.     shot=long(round(recnoSpn.linearInterp(fldr)))
  105.    
  106.     # If shot and tracf are valid, interpolate header values.
  107.     # The recnoSpn.txt file sets shot(fldr) values to -999999.  This
  108.     # causes the headers to be set to dummy values and later they will be
  109.     # removed using suwind.
  110.     if(shot>0 and tracf<97):
  111.         ep=shot
  112.         # artificial coordinates are computed for all the traces.  This avoids
  113.         # a lot of problems with projection from lat/long to coordinates.  
  114.         # That standard projection for the National Petroleum Reserve Alaska
  115.         # produces xy coordinates that are distorted enough that
  116.         # sqrt(deltax^2 + deltay^2) is a couple percent different from the
  117.         # distances measured on the spheroid.  (You cannot project from a
  118.         # spheroid to a flat map without distortion)  These distortions would
  119.         # make problems in the (shot,group) to (cdp, offset) map.  This is
  120.         # all avoided my artificial coordinates for seismic processing then
  121.         # loading real world coordinates in the processed CDP data.
  122.  
  123.  
  124.         # smaller tracf are groups (receivers) with small x coordinates than
  125.         # the shot.
  126.         roffset=(float(tracf)-((96.0+1.0)/2.0))*110.0
  127.         offset=long(round(roffset))
  128.         # shot x is shot number * 440 shot interval
  129.         r_sx=float(ep)*440.0
  130.         sx=long(round(r_sx))
  131.         # shot and group y coordinates are all 0
  132.         sy=0
  133.         gx=long(round(r_sx+roffset))
  134.         gy=0
  135.         # cdp computed from shot/group midpoint
  136.         cdp=long(round((float(sx+gx)/2.0-55.0/2.0)/55.0-752+101))
  137.         sutracf=long(round((gx/440.0+55.0/440.0)*4.0))
  138.         shotSpn=float(sx)/440.0
  139.         gSpn=float(gx)/440.0
  140.  
  141.         # elevation at the shot
  142.         selev=long(round(spnElev.linearInterp(shotSpn)))
  143.         # elevation at the group (receiver)
  144.         gelev=long(round(spnElev.linearInterp(gSpn)))
  145.  
  146.         # observer log says shot holes 82.5 ft before spn 123, then changes to
  147.         # 67.5 ft.
  148.         if(shotSpn<123):
  149.             sdepth=long(round(82.5))
  150.         else:
  151.             sdepth=long(round(67.5))
  152.  
  153.         # Compute shot and receiver statics to sea level using 10000 ft/s
  154.         # Convert to ms.
  155.         sstat=long(round((-selev+sdepth)*1000.0/10000.0))
  156.         gstat=long(round(-gelev*1000.0/10000.0))
  157.         tstat=long(round((-gelev-selev+sdepth)*1000.0/10000.0))
  158.  
  159.     # Code paths for bad and good traces merge again here.
  160.     # Print the header values to standard output.
  161.     print str(ep)              \
  162.          + " " + str(sx)      \
  163.          + " " + str(sy)      \
  164.          + " " + str(gx)      \
  165.          + " " + str(gy)      \
  166.          + " " + str(cdp)     \
  167.          + " " + str(sutracf) \
  168.          + " " + str(offset)  \
  169.          + " " + str(selev)   \
  170.          + " " + str(gelev)   \
  171.          + " " + str(sstat)   \
  172.          + " " + str(gstat)   \
  173.          + " " + str(tstat)

Tirandome el siguiente error
Código:
  
  File "./InterpText.py", line 161
    print str(ep)              \
            ^
SyntaxError: invalid syntax
¿Alguien sería tan amable de echarme una mano? Aportaré todo lo posible de mi parte para corregir este error. Me encuentro usando python-3.2.3-3 bajo un sistema Arch Linux x86.

Saludos
  #2 (permalink)  
Antiguo 28/09/2012, 08:11
AlvaroG
Invitado
 
Mensajes: n/a
Puntos:
Respuesta: SyntaxError: invalid syntax programa InterpText.py

Si no hubieses mencionado que usabas Python 3, habría pasado por alto el problema

En Python 3, print es una función, por lo que debes llamarla con sus argumentos entre paréntesis.


Saludos.
  #3 (permalink)  
Antiguo 28/09/2012, 10:05
 
Fecha de Ingreso: septiembre-2012
Ubicación: Tu corázon
Mensajes: 3
Antigüedad: 11 años, 6 meses
Puntos: 0
Respuesta: SyntaxError: invalid syntax programa InterpText.py

Cita:
Iniciado por AlvaroG Ver Mensaje
Si no hubieses mencionado que usabas Python 3, habría pasado por alto el problema

En Python 3, print es una función, por lo que debes llamarla con sus argumentos entre paréntesis.


Saludos.
Wow muchísimas gracias por la rápida respuesta. En efecto, el error era que los argumentos debían estar entre paréntesis. Sin embargo se me presento un nuevo problema. Esta vez:

Código:
File "./InterpText.py", line 82, in <module>
    tracl =long(tokens[0])

NameError: name 'long' is not defined
Tal vez sea un error básico pero apenas me estoy acoplando a esto de python. A lo mucho llevo 1 semana y media

Gracias por la atención
  #4 (permalink)  
Antiguo 28/09/2012, 11:44
AlvaroG
Invitado
 
Mensajes: n/a
Puntos:
Respuesta: SyntaxError: invalid syntax programa InterpText.py

Pues es de nuevo el mismo problema: en Python 3 no existe el tipo long (y por lo tanto tampoco existe la función para convertir un número a long), solamente int.

Te recomiendo leer [1] y [2], ya que parece que estás corriendo en python 3 un código ya hecho para python 2. Tienes a tu disposición el script 2to3 [3] que convierte código fuente de una versión a otra, aunque quizás lo mejor es que instales python 2.7.

[1] http://docs.python.org/py3k/whatsnew/3.0.html
[2] http://wiki.python.org/moin/Python2orPython3
[3] http://docs.python.org/library/2to3.html


Saludos.
  #5 (permalink)  
Antiguo 28/09/2012, 12:09
 
Fecha de Ingreso: septiembre-2012
Ubicación: Tu corázon
Mensajes: 3
Antigüedad: 11 años, 6 meses
Puntos: 0
Respuesta: SyntaxError: invalid syntax programa InterpText.py

Cita:
Iniciado por AlvaroG Ver Mensaje
Pues es de nuevo el mismo problema: en Python 3 no existe el tipo long (y por lo tanto tampoco existe la función para convertir un número a long), solamente int.

Te recomiendo leer [1] y [2], ya que parece que estás corriendo en python 3 un código ya hecho para python 2. Tienes a tu disposición el script 2to3 [3] que convierte código fuente de una versión a otra, aunque quizás lo mejor es que instales python 2.7.

[1] [url]http://docs.python.org/py3k/whatsnew/3.0.html[/url]
[2] [url]http://wiki.python.org/moin/Python2orPython3[/url]
[3] [url]http://docs.python.org/library/2to3.html[/url]


Saludos.
¡Gracias AlvaroG! ¡Muchísimas gracias! Problema resuelto y programa corriendo. Me pondré a leer toda la documentación, no sabía que había grandes diferencias entre python2 y python3. ¿Es necesario marcar el thread como resuelto y cerrarlo?

¡Saludos y de nuevo gracias!
  #6 (permalink)  
Antiguo 28/09/2012, 12:38
AlvaroG
Invitado
 
Mensajes: n/a
Puntos:
Respuesta: SyntaxError: invalid syntax programa InterpText.py

Cita:
Iniciado por TUDz Ver Mensaje
¿Es necesario marcar el thread como resuelto y cerrarlo?
Nopes, no tenemos esa regla en FdW :)

Etiquetas: invalid, syntax
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 07:20.