TipiWiki2

[ PyThon.2009-07-08-13-16 ]

edit | Recent Changes | Find Page | All Pages | Front Page |

Hinweis:
bei einfachen Problemen erstmal auf die "Einführungen" schauen. Offizielle Python Distribution http://www.python.org/, Hilfe hier http://www.python.org/doc/
Umgebung: IDLE (unter Win und Linux)

Einführungen:

http://rgruet.free.fr/ (super!)
http://www.thomas-guettler.de/vortraege/python/einfuehrung.html
http://www.silverymoon.de/uni/python/node1.html

Programmieren Lernen m. Python

http://www.freenetpages.co.uk/hp/alan.gauld/german/
Super! Hierin wird auch beschrieben, wie man mit Tk - in Python enthalten - GUI's programmiert.

http://www.cl.uni-heidelberg.de/kurs/skripte/prog1/html/index.html
komplettes Skript zur Python Programmierung (inkl. GUI)

http://www.wspiegel.de/pykurs/pykurs.htm
Nette Seite,u.a. zu Python / TkInter von einem Gymi-Lehrer

Python Troubleshooting

http://plone.org/documentation/tutorial/creating-custom-style/troubleshooting

: bad interpreter: Datei oder Verzeichnis nicht gefunden
so verweist die erste Zeile des Skripts auf eine nicht auffindbare Datei. Lösung:
Starten doch mit
$ python meinskript.py
oder mit vollem Pfad auf den Python Interpreter, z.B.
$ /usr/local/bin/python meinskript.py

Python + Gui

http://de.wikibooks.org/wiki/Python-Programmierung:_GUI_Programmierung
Prima, verschiedene GUI's im Vergleich.

http://ocemp.sourceforge.net/gui.html
GUI für Pygame (http://www.pygame.org)

Code-Schnipsel

Indexing, Slicing

s = 'albrechtdürer', s[1], s[2:], s[:6], s[3:5]

Tupel, Strings (Unveränderliche Datentypen)


Listen, Dictionaries (Veränderbare Datentypen)

a = [1,2,3,'frei']
a.sort, a.index(4), a.index('frei'), del(a[3])

d = {'blau' : 2, 'grün' : 3}
d['rot'] = {'hellrot' : 23, 'dunkelrot' : 2}
d['rot']['hellrot'] = 1
d.has_key['hellrot']
d['rot'].has_key['hellrot']
d.keys()
len(d)

http://rgruet.free.fr/#QuickRef

Dateien konvertieren

Beispiel: RGB-Tiff Datei in Graustufen umwandeln

#!/usr/local/bin/python
from os import *
from string import *
chdir('...') # in entspr. Verzeichnis wechseln
print getcwd()
d = listdir(curdir)
for f in d:
  fs = split(f,'.')
  #os_com = 'convert ' + fs[0] + '.ppm ' + fs[0] + '.tiff'
  # in Graustufen wandeln
  os_com = 'convert -colorspace gray ' + fs[0] + '.tiff ' + fs[0] + '.tiff'      
  print os_com
  # Linux Kommando ausführen
  fd = popen(os_com)

String in einer Datei durch anderen String ersetzen

#!/usr/local/bin/python
import re, string
filename = 'meinedatei.txt'
f = open(filename, 'r')

# Moeglichkeit 1: kompl. Datei einlesen
#txt = f.read()
### m = re.search('[0-9]*\.tiff', txt)
### print m.group(0)
#p = re.compile('[0-9]*\.tiff')
#m = p.findall(txt)
#m.sort(reverse=True)  # absteigend sortieren
#for i in m:
#  old = i.split('.')[0]
#  n = int(old)+1
#  new = '%08d' % n
#  txt = txt.replace(old,new)     # dauert zu lange (!)

# Moeglichkeit 2: Datei Zeilenweise einlesen
out=[]
while 1:
  line = f.readline()
  if not line:
    break
  m = re.search('[0-9]*\.tiff', line)
  if m:
    old = m.group(0).split('.')[0]   # in: "00000001.tiff" => old = "00000001"
    n = int(old)+17                  #      00000001 => 00000018
    new = '%08d' % n                 # Zahl-Formatierung auf 8 führende Nullen
    print old + " => " + new
    line = string.replace(line,old,new)
  out.append(line)

#fertig = "\n".join(out)
fertig = "".join(out)
#print fertig
f1 = open(filename + '.1','w')
f1.write(fertig)

Verzeichnisse einlesen, letzte Datei darin, diese Python Datei ausführen und die locals()-Variablen darin auswerten:

#!/usr/local/bin/python
from os import *

sum_images=0
sum_labels=0
sum_medx=0
sum_medy=0

def getDict(file):
 """
 executes the given file and returns the dictionary
 """
 d = {}
 execfile(file, {}, d)
 return d

def get_info():
   images=0
   labels=0
   sumx=0
   sumy=0
   array_xy=[]
   #for i in globals()["children"][0]["children"]:
   for i in d["children"][0]["children"]:
       images +=1
       for j in i["children"]:
           labels +=1
           minrow = j["minrow"]
           maxrow = j["maxrow"]
           mincol = j["mincol"]
           maxcol = j["maxcol"]
           sizex = maxcol-mincol
           sizey = maxrow-minrow
           array_xy.append([sizex, sizey])

           sumx+=sizex
           sumy+=sizey
   medx=sumx/labels
   medy=sumy/labels

   array_xy.sort()
   print "no. of (a) images=" + str(images) + ", (b) labels=" + str(labels)
   #print array_xy
   s = "lsize min [" + str(array_xy[0][0]) + "," + str(array_xy[0][1]) + "] "
   s += "med [" + str(medx) + "," + str(medy) + "] "
   s += "max [" + str(array_xy[labels-1][0]) + "," + str(array_xy[labels-1][1]) + "]"
   print s 
   return [images,labels,medx,medy]    # mehrere Rueckgabewerte in einem array

# Verzeichnisse
idir=0
d = listdir(curdir)
for dd in d:
   if dd.find('Noname') > 0:
       idir+=1
       f = listdir(curdir + "//" + dd)
       f.sort(reverse=True)            # nimm die aktuellste Config-Datei
#        if f.find('~') > 0:
#        if f[0].find("~"):
#            f.pop(0)
#            print f[1]
       print "(" + str(idir) + ") sequence=" + f[0]
       d = getDict(dd + "//" + f[0])
       ret = get_info()
       sum_images+=ret[0]
       sum_labels+=ret[1]
       sum_medx+=ret[2]
       sum_medy+=ret[3]
       print ""

print "sum of images:" + str(sum_images)
print "sum of labels:" + str(sum_labels)
print "medium labelsize: [" + str(sum_medx/idir) + "," + str(sum_medy/idir) + "]"