HispaLUG

El foro LUGnático => Software y LEGO Multimedia => Mensaje iniciado por: Yago en 01 de Enero de 2014, 20:33:29 PM

Título: Script para inventariar pedidos de BrickLink
Publicado por: Yago en 01 de Enero de 2014, 20:33:29 PM
Hace un par de noches aproveché 5 minutos para hacerme un script para registrar mejor los pedidos de BrickLink que he hecho para saber que piezas he pedido, cantidades, etc.

En estos momentos el script es muy simple, pero permite generar un Excel básico con "color y pieza" y "cantidad". Se necesita tener python instalado en el sistema (suele venir por defecto en plataformas Linux y Mac OS X, en windows también se puede instalar desde https://python.org/download/ (https://python.org/download/)

Más o menos así:










PieceQuantity
Black Antenna 1 x 4  Note: We may NOT differentiate this Part's Mold Variations. If you need a specific Variation, please ask.5
Black Bracket 1 x 2 - 1 x 2 Inverted10
......

Lo único que se necesita es generar un fichero llamado "Orders.txt" en el que incluir las líneas referentes a piezas del correo de orden de BrickLink, aquellas que son como estas:
Citar[New] Light Bluish Gray Plate 2 x 2  (x3) ..... EUR 0.04 each = EUR 0.12
[New] Light Bluish Gray Tile, Round 2 x 2 with Grille Fine Mesh Pattern  (x1) ..... EUR 0.20 each = EUR 0.20
[New] Yellow Plate, Round 2 x 2 with Axle Hole (New Style '+' Opening with X)  (x2) ..... EUR 0.08 each = EUR 0.16
...

Una vez ejecutado como se muestra:
Citar
python ./doit.py > Orders.csv

El resto es importar en Excel un fichero csv y separado por #.

El script es este:
Citar
#! /usr/bin/python

import sys
import re

dict = {}

f = open('Orders.txt', 'rU' )

for line in f:
   match = re.search( '^\[.*\]\s(.*)\s+\(x(\d*)\).*', line );

   if match:
       name = match.group(1)
       howmany = int(match.group(2))

       if name in dict:
           i = int(dict[name])
           dict[name] = i+howmany
       else:
           dict[name] = int(howmany)

f.close()

for key in dict:
   ## print 'Piece: ' + key + ' quantity: ' + str(dict[key])
   print key + '#' + str(dict[key])


Espero que os sea de utilidad y mejor no os asustéis cuando suméis la lista de piezas compradas  :disimulo: :disimulo:

Quizá siga añadiéndole alguna cosa: separar por color, intentar agrupar referencias iguales pero con distintas descripciones.. todo depende del tiempo que encuentre
Título: Re: Script para inventariar pedidos de BrickLink
Publicado por: WiWaEdu en 04 de Enero de 2014, 00:01:42 AM
No consigo ejecutarlo Yago! Siempre me da algún error, podrías detallar un poco mas como llegar a ejecutarlo?  :cejitas:
Título: Re: Script para inventariar pedidos de BrickLink
Publicado por: Yago en 06 de Enero de 2014, 17:38:06 PM
Por supuesto!

Veamos, primero de todo crear el fichero de entrada "Orders.txt" que debe contener todas las líneas de los pedidos tal que así:
Citar
[Used] Green Brick 2 x 4  (x1) ..... EUR 0.06 each = EUR 0.06
[Used] Tan Brick, Round 2 x 2  (x1) ..... EUR 0.06 each = EUR 0.06
[New] Black Plate 2 x 6  (x1) ..... EUR 0.0662 each = EUR 0.0662
[New] Black Plate, Modified 1 x 1 with Clip Light - Thick Ring #42 (x2) ..... EUR 0.0378 each = EUR 0.0756
[New] Black Plate, Modified 1 x 2 with 1 Stud (Jumper) *** May have Groove (3794b) *** (x2) ..... EUR 0.0462 each = EUR 0.0924
[New] Black Plate, Modified 1 x 2 with Door Rail  (x2) ..... EUR 0.0704 each = EUR 0.1408
[New] Black Slope 30 1 x 1 x 2/3  (x8) ..... EUR 0.084 each = EUR 0.672
[New] Black Slope 75 2 x 2 x 2 Quadruple Convex  (x1) ..... EUR 3.5847 each = EUR 3.5847
[New] Black Tap 1 x 1  (x1) ..... EUR 0.0745 each = EUR 0.0745
[New] Black Tile 2 x 2 with Groove  (x1) ..... EUR 0.1302 each = EUR 0.1302
[New] Bright Green Carrot Top  (x1) ..... EUR 0.2667 each = EUR 0.2667
...

Si hay diferentes pedidos no deben haber saltos de línea o líneas en blanco..

Luego asegurarte que tienes python instalado, abre una línea de comandos (ejecutar cmd.exe en windows o Terminal en linux/mac):
Citar
$ python -h

Debería devolver algo así:
Citar
serenity:_Orders yago$ python -h
usage: python [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-B     : don't write .py[co] files on import; also PYTHONDONTWRITEBYTECODE=x
-c cmd : program passed in as string (terminates option list)
-d     : debug output from parser; also PYTHONDEBUG=x
-E     : ignore PYTHON* environment variables (such as PYTHONPATH)
-h     : print this help message and exit (also --help)
-i     : inspect interactively after running script; forces a prompt even
         if stdin does not appear to be a terminal; also PYTHONINSPECT=x
-m mod : run library module as a script (terminates option list)
-O     : optimize generated bytecode slightly; also PYTHONOPTIMIZE=x
-OO    : remove doc-strings in addition to the -O optimizations
-R     : use a pseudo-random salt to make hash() values of various types be
         unpredictable between separate invocations of the interpreter, as
         a defense against denial-of-service attacks
-Q arg : division options: -Qold (default), -Qwarn, -Qwarnall, -Qnew
-s     : don't add user site directory to sys.path; also PYTHONNOUSERSITE
-S     : don't imply 'import site' on initialization
-t     : issue warnings about inconsistent tab usage (-tt: issue errors)
-u     : unbuffered binary stdout and stderr; also PYTHONUNBUFFERED=x
         see man page for details on internal buffering relating to '-u'
-v     : verbose (trace import statements); also PYTHONVERBOSE=x
         can be supplied multiple times to increase verbosity
-V     : print the Python version number and exit (also --version)
-W arg : warning control; arg is action:message:category:module:lineno
         also PYTHONWARNINGS=arg
-x     : skip first line of source, allowing use of non-Unix forms of #!cmd
-3     : warn about Python 3.x incompatibilities that 2to3 cannot trivially fix
file   : program read from script file
-      : program read from stdin (default; interactive mode if a tty)
arg ...: arguments passed to program in sys.argv[1:]

Other environment variables:
PYTHONSTARTUP: file executed on interactive startup (no default)
PYTHONPATH   : ':'-separated list of directories prefixed to the
               default module search path.  The result is sys.path.
PYTHONHOME   : alternate <prefix> directory (or <prefix>:<exec_prefix>).
               The default module search path uses <prefix>/pythonX.X.
PYTHONCASEOK : ignore case in 'import' statements (Windows).
PYTHONIOENCODING: Encoding[:errors] used for stdin/stdout/stderr.
PYTHONHASHSEED: if this variable is set to 'random', the effect is the same
   as specifying the -R option: a random value is used to seed the hashes of
   str, bytes and datetime objects.  It can also be set to an integer
   in the range [0,4294967295] to get hash values with a predictable seed.
serenity:_Orders yago$

Si el interprete de python funciona correctamente lo siguiente ya es ejecutarlo mediante
Citar
python ./doit.py > Orders.csv

o

Citar
python doit.py > Orders.csv

alternativamente se puede hacer sin el "> Orders.csv" y copiar todo la salida..

El resto es excel..

dónde te quedas?
Título: Re: Script para inventariar pedidos de BrickLink
Publicado por: WiWaEdu en 07 de Enero de 2014, 10:49:21 AM
Ya lo he conseguido, mi problema es que lo ejecutaba dentro del terminal de python.

Ahora me sale este error:

Citar
C:\>python doit.py > Orders.csv
  File "doit.py", line 27
    print key + '#' + str(dict[key])
            ^
SyntaxError: invalid syntax
Título: Re: Script para inventariar pedidos de BrickLink
Publicado por: Yago en 08 de Enero de 2014, 10:07:04 AM
quizá en windows key es una palabra reservada? ni idea.. prueba esta versión:

Citar
#! /usr/bin/python

import sys
import re

dict = {}

f = open('Orders.txt', 'rU' )

for line in f:
    match = re.search( '^\[.*\]\s(.*)\s+\(x(\d*)\).*', line );

    if match:
        name = match.group(1)
        howmany = int(match.group(2))

        if name in dict:
            i = int(dict[name])
            dict[name] = i+howmany
        else:
            dict[name] = int(howmany)

f.close()

for k in dict:
    ## print 'Piece: ' + k + ' quantity: ' + str(dict[k])
    print k + '#' + str(dict[k])