12 Commits
teil20 ... 1.00

Author SHA1 Message Date
b655926202 teil25 vom develop 2024-03-12 15:54:48 +01:00
0d63af7bbc endgültige Versionen. 2024-03-12 15:53:19 +01:00
504013d890 phone.py 2024-02-07 07:24:08 +00:00
65eb1436d6 tungen für RegEx.e Bitte geben Sie eine Commit-Beschreibung für Ihre Änderungen ein. Zeilen, 2024-02-07 08:21:15 +01:00
e2676beee0 Demoprogramme 2024-02-02 13:47:29 +01:00
3963f98baa Dateien umbenannt. 2024-02-02 11:48:10 +01:00
Olli Graf
c01833f411 teil24 angelegt. 2024-02-02 09:55:56 +01:00
Olli Graf
1dce636192 Programme für Diagrammtypen: Säule, gestapelte Säulen
Linien, gestapelte Balken, Torte
2024-01-17 14:19:16 +01:00
Olli Graf
2a998611bf share in .gitignore 2024-01-05 05:53:55 +01:00
0882dd06f3 Erster Schwung für Teil 22 2024-01-02 06:46:01 +01:00
ec60c85695 Readme updated 2023-12-11 07:50:37 +01:00
278d79f6d0 Code für Teil21 Interrupts 2023-12-11 07:49:21 +01:00
41 changed files with 3414 additions and 3 deletions

View File

@@ -25,4 +25,10 @@ CC-BY-SA Olli Graf
|18 | Generatoren und list comprehension|
|19 | Webseiten (Flask)|
|20 | virtuelle Umgebungen|
|22 | Numpy|
|23 | Matplotlib|
|24 | match|
|25 | Pandas|
|26 | Pygame|

View File

@@ -1,4 +1,4 @@
#!/home/pi/git/pythonkurs/teil20/bin/python
#!/home/pi/git/pythonkurs/teil20/bin/python3
# -*- coding: utf-8 -*-
import re
import sys

View File

@@ -1,4 +1,4 @@
#!/home/pi/git/pythonkurs/teil20/bin/python
#!/home/pi/git/pythonkurs/teil20/bin/python3
# -*- coding: utf-8 -*-
import re
import sys

View File

@@ -1,4 +1,4 @@
#!/home/pi/git/pythonkurs/teil20/bin/python
#!/home/pi/git/pythonkurs/teil20/bin/python3
# -*- coding: utf-8 -*-
import re
import sys

19
teil21/alarm.py Executable file
View File

@@ -0,0 +1,19 @@
#! /usr/bin/python3
# encoding:utf-8
import signal
import time
def handle_alarm(signum, frame):
print(f'Alarm ausgelöst bei {time.ctime()}')
signal.signal(signal.SIGALRM,handle_alarm)
signal.alarm(3)
print(f'aktuelle Zeit Start: {time.ctime()}')
time.sleep(13)
print(f'aktuelle Zeit Ende: {time.ctime()}')

41
teil21/interrupts.py Executable file
View File

@@ -0,0 +1,41 @@
#! /usr/bin/python3
import time
import signal
import sys
#Behandlung von SIGINT (CTRL-C)
def handle_sigint(signum, frame) :
print(f'Handling signal {signum} ({signal.Signals(signum).name}).')
if signum == signal.SIGINT:
print(f'SIGINT wird behandelt. {frame}')
time.sleep(1)
sys.exit(0)
#Behandlung von SIGTSTP (CTRL-Z)
def handle_sigtstp(signum,frame):
print(f'Behandle signal {signum} ({signal.Signals(signum).name}).')
print('Programm in Hintergrund')
# Behandlung von SiGCONT
def handle_sigcont(signum,frame):
print(f'Behandle signal {signum} ({signal.Signals(signum).name}).')
print('Programm im Vordergrund')
if __name__ == '__main__':
# Interrupt Handler registrieren
signal.signal(signal.SIGINT, handle_sigint)
signal.signal(signal.SIGTSTP, handle_sigtstp)
signal.signal(signal.SIGCONT, handle_sigcont)
for i in range(0,10000000):
print(f'Schleife: {i}')
time.sleep(0.5)
print('Schleifenende')

4
teil22/.gitignore vendored Normal file
View File

@@ -0,0 +1,4 @@
# created by virtualenv automatically
__pycache__
bin
lib

18
teil22/StressFile.py Normal file
View File

@@ -0,0 +1,18 @@
import io
import numpy as np
class StressFile:
def readOutFile(self,filename):
result = {
'frequency': [],
'temperatures': []
}
with open(filename,'r') as f:
content = f.readlines()
print(f'conent= {content}')
sf = StressFile()
sf.readOutFile('./kodos.out')

42
teil22/calc_array.py Normal file
View File

@@ -0,0 +1,42 @@
import numpy as np
# Array initialisieren
org = np.array([1,2,3,4,5,6])
# Kopiert das int64 Array in ein float64 Array
def copy_to_float64(source):
liste = []
for i in range(source.shape[1]):
liste.append(float(source[i]))
return np.array(liste,dtype=float64)
# Ein paar Kopien anlegen
copy_sum = org.copy()
copy_mult = org.copy()
copy_diff = org.copy()
copy_div = org.astype(np.float64).copy()
# Zu allen Elementen 2 dazuzählen
copy_sum += 2
print(f'copy_sum={copy_sum}')
# Alle Elemente mit 2 multiplizieren
copy_mult *= 2
print(f'copy_mult={copy_mult}')
# Von allen Elementen 1 abziehen
copy_diff -= 1
print(f'copy_diff={copy_diff}')
copy_div /=2
print(f'copy_div={copy_div}')

20
teil22/copyarray.py Normal file
View File

@@ -0,0 +1,20 @@
import numpy as np
org = np.array([1,2,3,4,5,6])
copy = org
print(f'org= {org}')
print(f'copy={copy}')
copy[2]= 7
print(f'org= {org}')
print(f'copy={copy}')
copy2 = org.copy()
copy2[2]= 3
print(f'org= {org}')
print(f'copy2={copy2}')

9
teil22/reshape.py Normal file
View File

@@ -0,0 +1,9 @@
import numpy as np
a = np.array([1,2,3,4,5,6,7,8,9,10])
print(f'orignal {a}')
reshaped = a.reshape(2,5)
print(f'reshaped {reshaped}')

7
teil22/rndm.py Normal file
View File

@@ -0,0 +1,7 @@
import numpy as np
#Erzeuge 1 Mio Zufallszahlen
random_np = np.random(100000)
random_list = list(random_np)

6
teil22/shape.py Normal file
View File

@@ -0,0 +1,6 @@
import numpy as np
twodim_array = np.array([[1,2,3,4,5],[1,4,9,16,25]])
print(f'shape is {twodim_array.shape}')

9
teil22/simplearray.py Normal file
View File

@@ -0,0 +1,9 @@
import numpy as np
simple_array = np.array([1,2,3,4,5,6])
print(f'simple_array={simple_array}')
print(f'ndim={simple_array.ndim}')
print(f'dtype={simple_array.dtype}')
print(f'shape is {simple_array.shape}')

9
teil22/twodimarray.py Normal file
View File

@@ -0,0 +1,9 @@
import numpy as np
twodim_array = np.array([[1,2,3,4,5],[1,4,9,16,25]],dtype='int32')
print(f'twodim_array={twodim_array}')
print(f'ndim={twodim_array.ndim}')
print(f'dtype={twodim_array.dtype}')
print(f'shape is {twodim_array.shape}')

6
teil23/.gitignore vendored Normal file
View File

@@ -0,0 +1,6 @@
# created by virtualenv automatically
__pycache__
bin
lib
share
*.csv

20
teil23/iospeed_balken.py Executable file
View File

@@ -0,0 +1,20 @@
#! ./bin/python
#encoding: utf-8
import matplotlib.pyplot as plt
import numpy as np
labels = [ 'Pineberry Pi pcie1_gen=2','Pineberry Pi pcie1_gen=3', 'MicroSD Raspi 5', 'MicroSD Raspi 4']
io_read= np.array([148.50,171.99,30.85,10.15])
io_write = np.array([99.15,114.97,20.45,6.63])
legend = ['Schreiben','Lesen']
#Höhe der Balken
__hoehe__ =0.6
fig,ax = plt.subplots()
plt.barh(labels,io_write,__hoehe__)
plt.barh(labels,io_read,__hoehe__,left=io_write)
plt.legend(legend)
plt.show()

30
teil23/normparabel_graph.py Executable file
View File

@@ -0,0 +1,30 @@
#! ./bin/python
# encoding:utf-8
import matplotlib.pyplot as plt
import numpy as np
def plot_normal_parabel():
# Erzeuge Datenpunkte für x-Werte von -10 bis 10
x = np.linspace(-3, 3, 100)
# Berechne die y-Werte für die Normalparabel
y = x**2
# Erstelle das Diagramm
plt.plot(x, y, label='Normalparabel: $y=x^2$')
# Beschriftungen und Titel hinzufügen
plt.xlabel('x-Achse')
plt.ylabel('y-Achse')
plt.title('Normalparabel')
# Legende hinzufügen
plt.legend()
# Funktion aufrufen, um die Normalparabel zu zeichnen
plot_normal_parabel()
# Diagramm anzeigen
plt.grid(True)
plt.show()

8
teil23/pyvenv.cfg Normal file
View File

@@ -0,0 +1,8 @@
home = /usr/bin
implementation = CPython
version_info = 3.11.2.final.0
virtualenv = 20.17.1+ds
include-system-site-packages = false
base-prefix = /usr
base-exec-prefix = /usr
base-executable = /usr/bin/python3

45
teil23/sinus_parabel_graph.py Executable file
View File

@@ -0,0 +1,45 @@
#! ./bin/python
# encoding:utf-8
import matplotlib.pyplot as plt
import numpy as np
def plot_normal_parabel():
# Erzeuge Datenpunkte für x-Werte von -10 bis 10
x = np.linspace(-3, 3, 100)
# Berechne die y-Werte für die Normalparabel
y = x**2
# Erstelle das Diagramm
plt.plot(x, y, label='Normalparabel: $y=x^2$')
# Beschriftungen und Titel hinzufügen
plt.xlabel('x-Achse')
plt.ylabel('y-Achse')
plt.title('Normalparabel')
# Legende hinzufügen
plt.legend()
def plot_sinus_function():
# Erzeuge Datenpunkte für x-Werte von -2π bis 2π
x = np.linspace(-2 * np.pi, 2 * np.pi, 100)
# Berechne die y-Werte für die Sinusfunktion
y = np.sin(x)
# Erstelle das Diagramm für die Sinusfunktion
plt.plot(x, y, label='Sinusfunktion: $y = \sin(x)$', color='blue')
# Legende hinzufügen
plt.legend()
# Funktion aufrufen, um die Normalparabel zu zeichnen
plot_normal_parabel()
plot_sinus_function()
# Diagramm anzeigen
plt.grid(True)
plt.show()

24
teil23/test.py Normal file
View File

@@ -0,0 +1,24 @@
# encoding: utf-8
import numpy as np
import matplotlib.pyplot as plt
# Koordinaten
x = np.arange(5, 10)
y = np.arange(12, 17)
print(f'x={x}')
print(f'y={y}')
# Plot
plt.plot(x,y)
# Titel hinzufügen
plt.title("Matplotlib PLot NumPy Array")
# Beschriftung für die Achsen
plt.xlabel("x Achse")
plt.ylabel("y Achse")
# Fenster anzeigen
plt.show()

23
teil23/verkauf_stapel.py Executable file
View File

@@ -0,0 +1,23 @@
#! ./bin/python
#encoding: utf-8
import matplotlib.pyplot as plt
import numpy as np
jahre= np.array(['2018','2019', '2020'])
aepfel= np.array([1000,1500,2000])
erdbeeren =np.array([500,950,900])
bananen=np.array([400,800,750])
breite = 0.6
fig,ax = plt.subplots()
#ax.legend('Verkäufe')
ax.bar(jahre,bananen,color='yellow')
ax.bar(jahre,erdbeeren,bottom=bananen,color='red')
ax.bar(jahre,aepfel,bottom=erdbeeren,color='green')
plt.legend(['Bananen','Erdbeeren','Äpfel'])
plt.show()

47
teil23/vornamen_reader.py Normal file
View File

@@ -0,0 +1,47 @@
#encoding: utf-8
def read_vornamen(filename):
dict = {}
# Der Zähler dient nur dazu, die erste Zeile zu überspringen
count = 0
dict['mädchen'] = 0
dict['jungs'] = 0
dict['divers'] = 0
with open(filename,'r') as f:
for zeile in f:
if count >0:
# einzelne Zeile in seine Bestandteile zerlegen
splitted = zeile.strip().split(';')
anzahl = splitted[0]
vorname = splitted[1]
geschlecht= splitted[2]
position = splitted[3]
if geschlecht == 'w':
dict['mädchen'] += 1
elif geschlecht == 'm':
dict['jungs'] += 1
else:
dict['divers'] += 1
data = {}
data['vorname'] = vorname
data['anzahl'] = int(anzahl)
data['geschlecht'] = geschlecht
data['position'] = position
if vorname not in dict:
dict[vorname] = data
else:
# doppelte Einträge summieren wir auf.
e = dict[vorname]
e['anzahl'] = int(anzahl) + (e['anzahl'])
count +=1
gesamt = dict['jungs'] + dict['mädchen'] + dict['divers']
dict['gesamt'] = gesamt
return dict

42
teil23/vornamen_sauelen.py Executable file
View File

@@ -0,0 +1,42 @@
#! ./bin/python
#encondig: utf-8
import matplotlib.pyplot as plt
from vornamen_reader import read_vornamen
def plot_geschlecht(vornamen):
bez= ['Mädchen', 'Jungs','divers']
geburten = [vornamen['mädchen'], vornamen['jungs'],vornamen['divers']]
print(f'geburten={geburten}')
farben = ['red','blue','green']
fig, ax = plt.subplots()
print(f'fig={fig}')
print(f'ax={ax}')
ax.bar(bez,geburten,label=bez, color=farben)
ax.set_ylabel('Geburten')
ax.set_title('Geburten nach Geschlecht Wuppertal 2020')
ax.legend(title='Geburten')
plt.show()
if __name__ == '__main__':
vornamen = read_vornamen('./Vornamen_Wuppertal_2020.csv')
jungs= vornamen['jungs']
maedels = vornamen['mädchen']
divers = vornamen['divers']
print(f'Jungs: {jungs}')
print(f'Mädchen: {maedels}')
print(f'divers: {divers}')
# print(f'vornamen={vornamen}')
plot_geschlecht(vornamen)

43
teil23/vornamen_torte.py Executable file
View File

@@ -0,0 +1,43 @@
#! ./bin/python
#encondig: utf-8
import matplotlib.pyplot as plt
import logging
from vornamen_reader import read_vornamen
logging.basicConfig( format='%(asctime)-15s [%(levelname)s] %(funcName)s: %(message)s', level=logging.INFO)
def plot_geschlecht(vornamen):
bez= ['Mädchen', 'Jungs','divers']
geburten = [vornamen['mädchen'], vornamen['jungs'],vornamen['divers']]
logging.info(f'geburten={geburten}')
proz_maedels = round(vornamen['mädchen'] / vornamen['gesamt'] *100,2)
proz_jungs = round(vornamen['jungs'] / vornamen['gesamt'] *100,2)
proz_divers = round(vornamen['divers'] / vornamen['gesamt'] *100,2)
farben = ['red','blue','green']
sizes= [proz_maedels,proz_jungs,proz_divers]
logging.info(f'sizes={sizes}')
fig, ax = plt.subplots()
ax.pie(sizes,explode=(0,0,0), labels=bez,autopct='%1.1f%%',shadow=True,startangle=90)
ax.axis('equal')
plt.show()
if __name__ == '__main__':
vornamen = read_vornamen('./Vornamen_Wuppertal_2020.csv')
jungs= vornamen['jungs']
maedels = vornamen['mädchen']
divers = vornamen['divers']
plot_geschlecht(vornamen)

6
teil24/.gitignore vendored Normal file
View File

@@ -0,0 +1,6 @@
# created by virtualenv automatically
__pycache__
bin
lib
share
*.csv

19
teil24/match_list.py Normal file
View File

@@ -0,0 +1,19 @@
def print_match(wert):
print(f'wert={wert}')
match wert:
case 1|2:
print('1 oder 2')
case 3|4:
print('3 oder 4')
case _:
print('unbekannt')
print_match(1)
print_match(3)
print_match(5)

11
teil24/match_structure.py Normal file
View File

@@ -0,0 +1,11 @@
values= ['John']
# Matching structure in Python switch-case
match values:
case [a]:
print(f'Only one item: {a}')
case [a, b]:
print(f'Two items: {a}, {b}')
case [a, b, c]:
print(f'Three items: {a}, {b}, and {c}')
case [a, b, c, *rest]:
print(f'More than three items: {a}, {b}, {c}, as well as: {rest}')

19
teil24/print_class.py Normal file
View File

@@ -0,0 +1,19 @@
def print_match(name):
print(f'name={name}')
match name:
case 'Lisa'|'Ralph'|'Janey':
print('zweite Klasse bei Ms. Hoover')
case 'Bart'|'Milhouse'|'Nelson':
print('vierte Klasse bei Ms. Krabappel')
case _:
print('unbekannt')
print_match('Lisa')
print_match('Milhouse')
print_match('Homer')

23
teil24/print_tag_elif.py Normal file
View File

@@ -0,0 +1,23 @@
import sys
num=5
def print_wochentag(num):
if num == 0:
print('Montag')
elif num == 1:
print('Dienstag')
elif num == 2:
print('Mittwoch')
elif num == 3:
print('Donnerstag')
elif num == 4:
print('Freitag')
elif num == 5:
print('Samstag')
elif num == 6:
print('Sonntag')
if __name__ == '__main__':
print_wochentag(int(sys.argv[1]))

28
teil24/print_tag_match.py Normal file
View File

@@ -0,0 +1,28 @@
import sys
num=5
def print_wochentag(num):
match num:
case 0:
print('Montag')
case 1:
print('Dienstag')
case 2:
print('Mittwoch')
case 3:
print('Donnerstag')
case 4:
print('Freitag')
case 5:
print('Samstag')
case 6:
print('Sonntag')
case _:
print('unbekannte Eingabe')
if __name__ == '__main__':
print_wochentag(int(sys.argv[1]))

View File

@@ -0,0 +1,28 @@
import sys
num=5
def print_wochentag(num):
match num:
case '0':
print('Montag')
case '1':
print('Dienstag')
case '2':
print('Mittwoch')
case '3':
print('Donnerstag')
case '4':
print('Freitag')
case '5':
print('Samstag')
case '6':
print('Sonntag')
case _:
print('unbekannte Eingabe')
if __name__ == '__main__':
print_wochentag(sys.argv[1])

23
teil24/print_type.py Normal file
View File

@@ -0,0 +1,23 @@
#encoding:utf-8
def print_type(value):
match value:
case int():
print('Integer')
case str():
print('String')
case list():
print('Liste')
case dict() as d:
print(f'Dictionary mit {len(d)} Einträgen')
case _:
print('unbekannter Datentyp')
print_type(1) #Integer
print_type('The Simpsons') # String
print_type([1, 2, 3]) # Liste
print_type({'a': 1, 'b': 2, 'c': 3}) # Dictionary
print_type(1.0) #float ist nicht implentiert

8
teil24/pyvenv.cfg Normal file
View File

@@ -0,0 +1,8 @@
home = /usr/bin
implementation = CPython
version_info = 3.11.2.final.0
virtualenv = 20.17.1+ds
include-system-site-packages = false
base-prefix = /usr
base-exec-prefix = /usr
base-executable = /usr/bin/python3

6
teil25/.gitignore vendored Normal file
View File

@@ -0,0 +1,6 @@
# created by virtualenv automatically
bin/
lib/
__pycache__
pyenv.cfg
*.bak

File diff suppressed because it is too large Load Diff

21
teil25/filter_vornamen.py Normal file
View File

@@ -0,0 +1,21 @@
from vornamen_reader import read_vornamen
import re
def print_vornamen_simple(vornamen):
for vorname in vornamen:
print(vorname)
def print_vornamen_filtered(vornamen,regex):
pattern = re.compile(regex)
for vorname in vornamen:
# print(f"{type(r)}: {r}")
# s = re.findall(regex,vorname)
# if s[0] != '':
is_match = pattern.match(vorname).span()[1] >0
if is_match:
print(f'{is_match}: {vorname}')
vornamen = read_vornamen('./Vornamen_Wuppertal_2020.csv')
#print_vornamen_simple(vornamen)
print_vornamen_filtered(vornamen,'O*')

22
teil25/phone.py Normal file
View File

@@ -0,0 +1,22 @@
import re
import unittest
class RegEx(unittest.TestCase):
pattern_phone = re.compile(r'\D')
pattern_digits_only = re.compile(r'\d')
def test_phone(self):
m = self.pattern_phone.sub('','+1 (212) 555-6832')
self.assertIsNotNone(self.pattern_digits_only.match(m))
print(f'm={m}')
if __name__ == '__main__':
unittest.main()

8
teil25/pyvenv.cfg Normal file
View File

@@ -0,0 +1,8 @@
home = /usr/bin
implementation = CPython
version_info = 3.11.2.final.0
virtualenv = 20.17.1+ds
include-system-site-packages = false
base-prefix = /usr
base-exec-prefix = /usr
base-executable = /usr/bin/python3

101
teil25/regex.py Normal file
View File

@@ -0,0 +1,101 @@
import re
import unittest
import logging
pattern_char_only = re.compile('^[A-Z][a-z]+$')
pattern_digits_only = re.compile(r'\d+')
pattern_no_digits = re.compile(r'\D+')
pattern_plz = re.compile('^[0-9]{5}$')
pattern_plz2 = re.compile('^\d{5}$')
pattern_quote= re.compile(':')
pattern_tab = re.compile(r'\t')
pattern_simpson = re.compile('Simpson')
pattern_simple = re.compile('O*')
logging.basicConfig( format='%(asctime)-15s [%(levelname)s] %(funcName)s: %(message)s', level=logging.DEBUG)
# Unittest für die Demonstration von regular expressions (re)
class TestRegEgEx(unittest.TestCase):
# match: Passt der String auf die re
def test_match(self):
m = pattern_char_only.match('Olli')
logging.debug(f'm={m}')
self.assertTrue(m.span()[1] >0)
# Sucht alle Vorkommnisse der re im String
def test_findall(self):
s = '5 Äpfel, 10 Bananen, 42 Erdbeeren'
logging.debug(f' nur Ziffern: {pattern_digits_only.findall(s)}')
logging.debug(f' keine Ziffern: {pattern_no_digits.findall(s)}')
m = pattern_char_only.findall('Olli')
logging.debug(f'm={m}')
self.assertIsNotNone(m)
# Prüft die Gültigkeit einer Postleitzahl ('^\d{5}$' genau 5 Ziffern)
def test_plz(self):
patterns = [pattern_plz,pattern_plz2]
plz = ['42275','5600']
for pattern in patterns:
m = pattern.findall(plz[0])
logging.debug(f'm={m}')
self.assertNotEqual('',m[0])
m = pattern.findall(plz[1])
logging.debug(f'm={m}')
self.assertEqual([],m)
# Test für Suche
def test_search(self):
m = pattern_char_only.search('Olli')
logging.debug(f'm={m}')
#String passt auf die regular expression
self.assertIsNotNone(m)
m = pattern_char_only.search('123456')
logging.debug(f'm={m}')
#Dieser String passt nicht.
self.assertIsNone(m)
# Test zum Splitting (der Satz wird am ':' in die Worte zerlegt)
def test_split(self):
m = pattern_quote.split(' Die:Würde:des:Menschen:ist:unantastbar.')
logging.debug(f'm={m}')
self.assertIsNotNone(m)
#Die einzelnen Worte ausgeben
for word in m:
logging.debug(f' Wort: {word}')
# Test für Ersetzung (substitution von Tab mit Space)
def test_sub(self):
m = pattern_tab.sub(' ','Satz\tmit\tTabulator.')
logging.debug(f'm={m}')
# Test für einfache regular Expression ('O*')
def test_simple_re(self):
m = pattern_simple.search('Olli')
logging.debug(f'm={m.span()}')
self.assertTrue(m.end() > 0)
m = pattern_simple.search('Luana')
logging.debug(f'm={m.span()}')
self.assertFalse(m.end() >0)
# Test für den Iterator ('*Simpson')
def test_finditer(self):
m = pattern_simpson.finditer('Homer Simpson, Marge Simpson, Bart Simpson, Lisa Simpson, Maggie Simpson')
logging.debug(f'm={m}')
# Die einzelnen gefunden Teilstrings ausgeben.
for name in m:
logging.debug(f'Name={name},Start bei: {name.start()}')
if __name__ == '__main__':
unittest.main()

50
teil25/vornamen_reader.py Normal file
View File

@@ -0,0 +1,50 @@
#encoding: utf-8
import re
def read_vornamen(filename):
dict = {}
# Der Zähler dient nur dazu, die erste Zeile zu überspringen
count = 0
pattern_csv = re.compile(';')
dict['mädchen'] = 0
dict['jungs'] = 0
dict['divers'] = 0
with open(filename,'r') as f:
for zeile in f:
if count >0:
# einzelne Zeile in seine Bestandteile zerlegen
splitted = pattern_csv.split(zeile.strip())
anzahl = splitted[0]
vorname = splitted[1]
geschlecht= splitted[2]
position = splitted[3]
if geschlecht == 'w':
dict['mädchen'] += 1
elif geschlecht == 'm':
dict['jungs'] += 1
else:
dict['divers'] += 1
data = {}
data['vorname'] = vorname
data['anzahl'] = int(anzahl)
data['geschlecht'] = geschlecht
data['position'] = position
if vorname not in dict:
dict[vorname] = data
else:
# doppelte Einträge summieren wir auf.
e = dict[vorname]
e['anzahl'] = int(anzahl) + (e['anzahl'])
count +=1
gesamt = dict['jungs'] + dict['mädchen'] + dict['divers']
dict['gesamt'] = gesamt
return dict