Skip to content
Snippets Groups Projects

Compare revisions

Changes are shown as if the source revision was being merged into the target revision. Learn more about comparing revisions.

Source

Select target project
No results found

Target

Select target project
No results found
Show changes
Showing
with 24494 additions and 3025 deletions
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
%% Cell type:markdown id: tags:
# Seminar Problemorientierte Programmierung
## 3 Extra: Reguläre Ausdrücke
Dieses Kapitel taucht nicht im englischen Python-Kurs auf und wird separat gepflegt.
In der Praxis können wir reguläre Ausdrücke nutzen, um in Texten zu suchen und Muster zu entdecken. Python bietet uns im `re`-Modul (re = Regular Expression = Regulärer Ausdruck) viele Funktionen an, um mit regulären Ausdrücken zu arbeiten.
Es gibt dabei zwei "Dimensionen" an denen wir uns "entlanghangeln" müssen: die Funktionen, die vom `re`-Modul bereitgestellt werden und die regulären Ausdrücke selber, die komplex werden können. Wir beginnen zunächst mit nur einer Funktion und werden Stück für Stück komplexere Ausdrücke kennenlernen. Danach schauen wir uns weitere Funktionen an.
### Ihre Lernziele
Beschreiben Sie in 2-3 Stichpunkten kurz was Sie im Seminar heute lernen wollen. Klicken Sie dazu doppelt auf diesen Text und bearbeiten Sie dann den Text:
-
-
-
### Exkurs: Was mir an Python gefällt
In einer Datei alle E-Mail-Adressen extrahieren geht recht einfach:
In ihrem Verzeichnis sollte eine Datei `test.txt` liegen. Öffnen Sie diese in einem Texteditor Ihrer Wahl. Schauen Sie jetzt, wie leicht man mit dem Modul `re` in Python E-Mail-Adressen extrahieren kann:
%% Cell type:code id: tags:
```
import re
def find_in_file(pattern, file):
reg_pattern = re.compile(pattern)
for line in file:
for found in reg_pattern.findall(line):
print(found[0])
find_in_file(r"([a-zA-Z0-9-!#$%&'*+-/=?^_`{|}~]+@([A-Za-z0-9-]+\.)+[a-zA-Z]{2,})", open("test.txt", "rt"))
```
%% Cell type:markdown id: tags:
### 3.1 Einfache Suche
Wir können mit der Funktion `findall` alle Teilzeichenketten in einer Zeichenkette finden, die auf ein gegebenes Muster (in Form eines regulären Ausdrucks) passen. Die Funktion erwartet zwei Argumente: einen regulären Ausdruck und die Zeichenkette, die durchsucht werden soll:
%% Cell type:code id: tags:
```
import re
re.findall(r'f[a-z]*', 'which foot or hand fell fastest')
```
%% Cell type:markdown id: tags:
1. In der ersten Zeile wird das `re`-Modul importiert. Das muss einmal am Anfang unseres Programms passieren. Hier im Jupyter-Notebook reicht es, wenn das Modul in einem Block importiert wird - sobald der Block ausgeführt wurde, kann es in allen folgenden Blöcken verwendet werden.
2. In der nächsten Zeile wird - mittels der Punkt-Notation - die `findall`-Funktion im `re`-Modul aufgerufen.
3. Der Funktion werden zwei Argumente übergeben: `r'f[a-z]*'` und `'which foot or hand fell fastest'`.
4. Das erste Argument ist ein regulärer Ausdruck. Reguläre Ausdrücke werden in Hochkommata `''` eingeschlossen und beginnen mit einem `r`.
5. Das heißt, der eigentliche reguläre Ausdruck lautet `f[a-z]*`. Dieser Ausdruck beschreibt Zeichenketten, die mit einem `f` beginnen und von beliebig vielen - auch 0! - (`*`) Kleinbuchstaben (`[a-z]`) gefolgt werden. Dabei beschreibt der Ausdruck `[a-z]` in eckigen Klammern ein Zeichen, welches die Werte `a` bis `z` haben darf, das `*` dahinter besagt, dass dieses Zeichen beliebig oft wiederholt werden darf.
6. Das zweite Argument (`'which foot or hand fell fastest'`) ist die Zeichenkette, in der wir nach Teilzeichenketten suchen, die auf den übergebenen regulären Ausdruck passen.
Das Ergebnis des Aufrufs von `findall` ist eine Liste der Teilzeichenketten, die auf das Muster passen - in unserem Beispiel sind das die Zeichenketten `foot`, `fell` und `fastest`.
Probieren Sie es hier selber aus:
%% Cell type:code id: tags:
```
regaus = r'f[a-z]*'
text = input("Geben Sie eine Zeichenkette zum Testen ein:")
ergebnis = re.findall(regaus, text)
if ergebnis:
print("Es wurden folgende Teilzeichenketten erkannt:", ergebnis)
else:
print("Leider wurde nichts erkannt, probieren Sie es noch einmal.")
```
%% Cell type:markdown id: tags:
Ändern Sie den regulären Ausdruck im folgenden Beispiel, so dass alle Wörter, die mit einem `b` beginnen ausgegeben werden:
%% Cell type:code id: tags:
```
re.findall(r'b', 'Wir bauten und bohrten bis das Haus fertig war.')
```
%% Cell type:markdown id: tags:
Die Ausgabe sollte so aussehen:
```
['bauten', 'bohrten', 'bis']
```
Ändern Sie den regulären Ausdruck, so dass jetzt nur Wörter ausgegeben werden, die mit einem `b` beginnen und mit einem `n` enden. Die Ausgabe sollte dann so aussehen:
```
['bauten', 'bohrten']
```
Welche Probleme sind bei Ihren Versuchen aufgetreten?
-
-
%% Cell type:markdown id: tags:
### 3.2 Schritt für Schritt: ein beliebiges Zeichen
Der Punkt `.` steht für ein beliebiges Zeichen:
%% Cell type:code id: tags:
```
re.findall(r'a.', "Am Anfang aßen wir alle Manna und Kartoffeln")
```
%% Cell type:markdown id: tags:
Im Satz `Am Anfang aßen wir alle Kartoffeln.` gibt es genau sechs Vorkommen von einem kleinen `a` mit einem Zeichen dahinter. Wie wir sehen, wird auch das `a` am Ende von `Manna`, welches von einem Leerzeichen gefolgt ist, erkannt. Das liegt daran, dass der Punkt für wirklich jedes Zeichen (auch das Leerzeichen) steht. Die zwei Zeichenketten `Am` und `An` werden nicht erkannt, da sie ein großes `A` enthalten, wir aber nach einem kleinen gesucht haben.
%% Cell type:markdown id: tags:
### 3.3 Und weiter
Sie kennen jetzt eine Funktion, um reguläre Ausdrücke in Python anzuwenden und damit Texte zu durchsuchen. Weitere Funktionen ermöglichen die Extraktion und das Ersetzen von Teilzeichenketten in Texten. Bevor wir diese Funktionen kennenlernen, ist es praktisch, mit regulären Ausdrücken vertraut zu werden. Eine sehr gute interaktive Übungsseite dazu finden Sie [hier](https://regexone.com/lesson/introduction_abcs). Arbeiten Sie diese Seite gemeinsam Schritt für Schritt durch. Schrecken Sie nicht vor dem englischen Text zurück - ich helfe Ihnen bei Fragen gerne weiter.
Es gibt noch viele andere gute Tutorials zu regulären Ausdrücken, z.B. [hier](https://ryanstutorials.net/regular-expressions-tutorial/) oder [hier](https://www.python-kurs.eu/re.php). Sie können auch eine dieser Anleitungen durcharbeiten, wenn Sie damit besser zurechtkommen.
%% Cell type:markdown id: tags:
### 3.4 weitere nützliche Funktionen des `re`-Moduls
Sie haben in den Tutorials einige regulären Ausdrücke kennengelernt. Nun können wir weitere Funktionen des `re`-Moduls benutzen. Im Folgenden werden mehrere Funktionen vorgestellt. Anschließend können Sie diese in Übungen testen.
%% Cell type:markdown id: tags:
#### 3.4.1 Suchen und Matchen
Die Funktion `findall(regex,string)` haben sie schon kennengelernt:
%% Cell type:code id: tags:
```
import re
re.findall(r'f[a-z]*', 'which foot or hand fell fastest')
```
%% Cell type:markdown id: tags:
Zudem gibt es eine Funktion `search(regex,string)`. Die Argumente sind diesselben wie bei `findall`.
Diese Funktion durchsucht eine Zeichenkette *string* nach dem Vorkommen eines Teilstrings, der auf den regulären Ausdruck *regex* passt. Der erste gefundene Teilstring wird zurückgeliefert. Die Rückgabe ist ein sogennantes *match-Objekt*.
%% Cell type:code id: tags:
```
import re
object1 = re.search(r'f[a-z]*', 'which foot or hand fell fastest')
object2 = re.search(r'f[a-z]*', 'The regex did not match anything.')
print(object1,"\n",object2)
```
%% Cell type:markdown id: tags:
Ein *match-Objekt* enthält die Methoden `group()`, `span()`, `start()` und `end()`, die man im folgenden Beispiel im selbsterklärenden Einsatz sieht:
%% Cell type:code id: tags:
```
object1 = re.search(r'f[a-z]*', 'which foot or hand fell fastest')
print(object1.group())
print(object1.span())
print(object1.start())
print(object1.end())
```
%% Cell type:markdown id: tags:
Es gibt zuletzt noch eine dritte Funktion `match(regex,string)`. Diese Funktion checkt, ob ein Teilstring, der auf den regulären Ausdruck *regex* passt, am Anfang der Zeichenkette *string* vorkommt, Die Rückgabe ist wieder ein *match-Objekt*.
%% Cell type:code id: tags:
```
object1 = re.match(r'f[a-z]*', 'foot or hand fell fastest')
object2 = re.match(r'f[a-z]*', 'which foot or hand fell fastest')
print(object2)
print(object1)
print(object1.group())
print(object1.span())
print(object1.start())
print(object1.end())
```
%% Cell type:markdown id: tags:
#### 3.4.1 Übung:
Denken Sie sich eine Zeichenkette und einen regulären Ausdruck aus, die die Unterschiede der drei kennengelernten Funktionen wiedergibt.
%% Cell type:code id: tags:
```
```
%% Cell type:markdown id: tags:
#### 3.4.2 Ersetzen
%% Cell type:markdown id: tags:
Das `re`-Modul stellt nicht nur Funktionen zum Durchsuchen von Zeichenketten zur Verfügung. Mit der Funktion `re.sub(regex, replacement, string)` kann man Teilstrings ersetzen. Jede Übereinstimmung des regulären Ausdrucks *regex* in der Zeichenkette *string* wird durch die Zeichenkette *replacement* ersetzt.
%% Cell type:code id: tags:
```
re.sub(r'f[a-z]*', 'beer', 'which foot or hand fell fastest')
```
%% Cell type:markdown id: tags:
#### 3.4.3 Kompilieren
Wenn man bestimmte reguläre Ausdrücke mehrmals benutzen möchte, kann man die Funktion `compile(regex)` benutzen. Diese Funktion kompiliert einen regulären Ausdruck *regex* in eine regex-Objekt. Dieses kann man dann für weitere Funktionen nutzen.
%% Cell type:code id: tags:
```
regex_1 = re.compile(r'f[a-z]*')
print(regex_1.findall('which foot or hand fell fastest'))
print(regex_1.search('which foot or hand fell fastest'))
print(regex_1.match('which foot or hand fell fastest'))
print(regex_1.sub('beer','which foot or hand fell fastest'))
```
%% Cell type:markdown id: tags:
### Aufgaben
#### Aufgabe 1
Schreiben Sie eine Funktion, die eine Zeichenkette als Parameter entgegennimmt und überprüft, ob die Zeichenkette nur Kleinbuchstaben und Zahlen enthält.
Benutzen Sie reguläre Ausdrücke und die obigen Funktionen.
%% Cell type:code id: tags:
```
```
%% Cell type:markdown id: tags:
#### Aufgabe 2
Schreiben Sie eine Funktion, die eine Zeichenkette als Parameter entgegennimmt und überprüft, ob die Zeichenkette einen Teilstring enthält, der aus einem "a" und nachfolgend aus mindestens einem "b" besteht. (z.B. "abb", "abbbbb", "abbbbbbbbbbbbbbbb").
Benutzen Sie reguläre Ausdrücke und die obigen Funktionen.
%% Cell type:code id: tags:
```
```
%% Cell type:markdown id: tags:
#### Aufgabe 3
Schreiben Sie eine Funktion, die eine Zeichenkette als Parameter entgegennimmt und alle darin enthaltenen Leerzeichen durch ein Minus ersetzt.
Benutzen Sie reguläre Ausdrücke und die obigen Funktionen.
%% Cell type:code id: tags:
```
```
%% Cell type:markdown id: tags:
#### Aufgabe 4
Schreiben Sie eine Funktion, die eine Zeichenkette *s* und eine natürliche Zahl *n* als Parameter entgegennimmt und alle Wörter der Länge n aus der Zeichenkette *s* entfernt.
Benutzen Sie reguläre Ausdrücke und die obigen Funktionen.
%% Cell type:code id: tags:
```
```
%% Cell type:markdown id: tags:
![Speichern](https://amor.cms.hu-berlin.de/~jaeschkr/teaching/spp/floppy.png) Speichern Sie dieses Notebook so, dass Ihre Änderungen nicht verlorengehen (nicht auf einem Pool-Rechner). Klicken Sie dazu oben links auf das Disketten-Icon und nutzen Sie beispielsweise einen USB-Stick, E-Mail, Google Drive, Dropbox oder Ihre [HU-Box](https://box.hu-berlin.de/).
%% Cell type:markdown id: tags:
![Smiley](https://upload.wikimedia.org/wikipedia/commons/a/a7/Emblem-fun.svg)
Herzlichen Glückwunsch! Sie haben das 3. Kapitel geschafft. Weiter geht es in [4: Fallstudie: Schnittstellenentwurf](seminar04.ipynb).
%% Cell type:markdown id: tags:
![CC-BY-NC](https://scm.cms.hu-berlin.de/ibi/python/-/raw/master/img/cc-by-nc.png)
Dieses Notebook ist als freies Werk unter der Lizenz [Creative Commons Attribution-NonCommercial 3.0 Unported](http://creativecommons.org/licenses/by-nc/3.0/) verfügbar. Sie dürfen die Inhalte kopieren, verteilen und verändern, solange Sie die Urheber nennen und sie nicht für kommerzielle Zwecke nutzen.
......
%% Cell type:markdown id: tags:
<h1>Table of Contents<span class="tocSkip"></span></h1>
<div class="toc"><ul class="toc-item"><li><span><a href="#Jupyter-Notebook-Grundlagen" data-toc-modified-id="Jupyter-Notebook-Grundlagen-1"><span class="toc-item-num">1&nbsp;&nbsp;</span>Jupyter Notebook Grundlagen</a></span><ul class="toc-item"><li><span><a href="#Standardbrowser" data-toc-modified-id="Standardbrowser-1.1"><span class="toc-item-num">1.1&nbsp;&nbsp;</span>Standardbrowser</a></span><ul class="toc-item"><li><span><a href="#Anleitungen" data-toc-modified-id="Anleitungen-1.1.1"><span class="toc-item-num">1.1.1&nbsp;&nbsp;</span>Anleitungen</a></span></li></ul></li><li><span><a href="#Shortcuts" data-toc-modified-id="Shortcuts-1.2"><span class="toc-item-num">1.2&nbsp;&nbsp;</span>Shortcuts</a></span><ul class="toc-item"><li><span><a href="#Beispiel:-Markdown-Zelle-vs.-Code-Zelle" data-toc-modified-id="Beispiel:-Markdown-Zelle-vs.-Code-Zelle-1.2.1"><span class="toc-item-num">1.2.1&nbsp;&nbsp;</span>Beispiel: Markdown Zelle vs. Code Zelle</a></span></li></ul></li></ul></li><li><span><a href="#Python-Grundlagen" data-toc-modified-id="Python-Grundlagen-2"><span class="toc-item-num">2&nbsp;&nbsp;</span>Python Grundlagen</a></span><ul class="toc-item"><li><span><a href="#Grundlegende-Datentypen" data-toc-modified-id="Grundlegende-Datentypen-2.1"><span class="toc-item-num">2.1&nbsp;&nbsp;</span>Grundlegende Datentypen</a></span></li><li><span><a href="#Listen" data-toc-modified-id="Listen-2.2"><span class="toc-item-num">2.2&nbsp;&nbsp;</span>Listen</a></span></li><li><span><a href="#Mengen" data-toc-modified-id="Mengen-2.3"><span class="toc-item-num">2.3&nbsp;&nbsp;</span>Mengen</a></span></li><li><span><a href="#Ranges" data-toc-modified-id="Ranges-2.4"><span class="toc-item-num">2.4&nbsp;&nbsp;</span>Ranges</a></span></li><li><span><a href="#Tupel" data-toc-modified-id="Tupel-2.5"><span class="toc-item-num">2.5&nbsp;&nbsp;</span>Tupel</a></span></li><li><span><a href="#Dictionaries" data-toc-modified-id="Dictionaries-2.6"><span class="toc-item-num">2.6&nbsp;&nbsp;</span>Dictionaries</a></span></li><li><span><a href="#If-Anweisungen" data-toc-modified-id="If-Anweisungen-2.7"><span class="toc-item-num">2.7&nbsp;&nbsp;</span>If-Anweisungen</a></span></li><li><span><a href="#Schleifen" data-toc-modified-id="Schleifen-2.8"><span class="toc-item-num">2.8&nbsp;&nbsp;</span>Schleifen</a></span></li><li><span><a href="#Funktionen" data-toc-modified-id="Funktionen-2.9"><span class="toc-item-num">2.9&nbsp;&nbsp;</span>Funktionen</a></span></li></ul></li><li><span><a href="#----------------Praktisch-für-Python,-aber-nicht-für-unseren-Kurs------------------" data-toc-modified-id="----------------Praktisch-für-Python,-aber-nicht-für-unseren-Kurs-------------------3"><span class="toc-item-num">3&nbsp;&nbsp;</span><font color="red">--------------- Praktisch für Python, aber nicht für unseren Kurs -----------------</font></a></span><ul class="toc-item"><li><span><a href="#Lambda-Funktionen" data-toc-modified-id="Lambda-Funktionen-3.1"><span class="toc-item-num">3.1&nbsp;&nbsp;</span>Lambda-Funktionen</a></span></li><li><span><a href="#List-Comprehensions" data-toc-modified-id="List-Comprehensions-3.2"><span class="toc-item-num">3.2&nbsp;&nbsp;</span>List Comprehensions</a></span></li><li><span><a href="#Klassen" data-toc-modified-id="Klassen-3.3"><span class="toc-item-num">3.3&nbsp;&nbsp;</span>Klassen</a></span></li></ul></li></ul></div>
%% Cell type:markdown id: tags:
# Grundlagen Jupyter Notebooks
Falls Sie im Python-Programmierkurs sind und dies ihr erstes geöffnetes Jupyter Notebook ist: Herzlichen Glückwunsch! :)
Falls Sie im Python-Programmierkurs sind und dies ihr erstes geöffnetes Jupyter Notebook ist, lesen Sie nur bis bis zum Kapitel "Python.Grundlagen". Danach wechseln Sie zum Notebook [seminar00.ipynb](seminar00.ipynb).
- Jupyter ist freie Software – ein browserbasiertes Tool für verschiedene Programmiersprachen (wir benutzen Python).
- Es stellt Quellcode, Visualisierungen, Text und Erklärungen in einem (Web-)Dokument – dem Jupyter Notebook – dar.
- Notebooks bestehen aus Blöcken bzw. "Zellen".
- Es gibt zwei Arten von Blöcken: "Code" ist für Python-Code, "Markdown" ist für Texte, die Sie mit Hilfe der [Markdown-Syntax](https://de.wikipedia.org/wiki/Markdown#Auszeichnungsbeispiele) formatieren können.
- Blöcke können "ausgeführt" werden, dabei wird der Python-Code ausgeführt und Markdown in HTML umgewandelt und angezeigt.
- Unterhalb eines Blocks mit Quellcode wird der Rückgabewert der letzten Anweisung ausgegeben.
- Quellcode kann auf mehrere Blöcke aufgeteilt werden (Variablen behalten ihre Gültigkeit/Sichtbarkeit).
- Sie können auf Text doppelt klicken, um sich den Markdown-Quellcode anzuzeigen. Probieren Sie es mit diesem Text aus.
- Durch die Tastenkombination "Strg" und "Enter" oder durch Drücken des "Run"-Buttons oben im Menü kommen Sie wieder in den Lesemodus
- Wenn Sie mal etwas "kaputtgespielt" haben, hilft es evtl., im "Kernel"-Menü den "Restart"-Eintrag auszuwählen.
## Standardbrowser
Bitte verwenden Sie **nicht** Safari oder Internet Explorer. Auch mit Windows Edge gab es in der Vergangenheit Probleme. Wir empfehlen die Verwendung von Firefox, aber auch Google Chrome lief in der Vergangenheit problemlos. Wenn Sie unsicher sind, was ihr aktueller Standardbrowser ist, folgen Sie einfach der folgenden Anleitung zum Ändern des Standardbrowsers und gehen Sie sicher, dass der richtige Standardbrowser ausgewählt ist.
### Anleitungen
**Änderung des Standardbrowsers in...**
*macOS:*
1. Öffnen sie die Systemeinstellungen.
2. Klicken Sie auf „Allgemein“.
3. Wählen Sie unter „Standard-Webbrowser“ den gewünschten Browser aus.
*Ubuntu Linux:*
1. Öffnen Sie die System Settings.
2. Klicken Sie auf „Applications“.
3. Wählen Sie in der linken Spalte „Default Applications“ aus.
4. Klicken Sie in der Spalte rechts davon auf „Web Browser“.
5. Wählen Sie „in the following browser:“ aus.
6. Wählen Sie den gewünschten Browser aus.
*Windows:*
1. Öffnen Sie die Systemsteuerung.
2. Klicken Sie auf „Standardprogramme“.
3. Klicken Sie auf „Standardprogramme festlegen“.
4. Klicken Sie in der Liste auf den gewünschten Browser.
5. Klicken Sie dann auf „Dieses Programm als Standard festlegen“.
%% Cell type:markdown id: tags:
## Shortcuts
**Bitte probieren Sie alle unten stehenden Befehle und verstehen Sie, was gemacht wird. Das ist die Basis, die Sie für das Arbeiten mit Jupyter Notebooks brauchen.**
Übersicht: *Menü Help -> Keyboard Shortcuts*
Wichtigste Shortcuts:
- *Enter*: Editiermodus für selektierte Zelle (grün umrandet)
- *Esc*: Editiermodus verlassen/Kommandomodus (blau umrandet)
- *Strg + Enter*: Selektierte Zelle ausführen
- *Shift + Enter*: Selektierte Zelle ausführen und in nächste Zelle springen
Im Editiermodus:
- *Tab*: Autocomplete oder Einrücken
- *Shift + Tab*: Einrücken rückwärts
Im Kommando-/Lesemodus:
- *B*: Zelle darunter einfügen
- *A*: Zelle darüber einfügen
- *DD*: Zelle löschen
- *M*: Zelltyp Markdown (für formatierte beschreibende Texte, zB diese Zelle)
- *Y*: Zelltyp Code (Default)
%% Cell type:code id: tags:
```
```
%% Cell type:markdown id: tags:
%% Cell type:markdown id: tags:
### Beispiel: Markdown Zelle vs. Code Zelle
%% Cell type:markdown id: tags:
Dies ist eine **Markdown Zelle**. Hier kann jeglicher Text geschrieben werden. Durch Strg+Enter wird er in den Lesemodus gebracht, durch ein einfach Enter (oder Doppelklick) in den Editiermodus.
Hier werden keine Rechnungen ausgeführt, siehe:
5+3
In diesen Feldern werden Erklärungen, Aufgabenstellungen und schriftliche Antworten von euch stehen.
%% Cell type:code id: tags:
```
# Das ist eine **Code Zelle**, bei Strg+Enter wird die folgende Rechnung ausgeführt und darunter angezeigt
# Mit Enter kommt man in den Editiermodus, mit Strg+Enter wird der Code ausgeführt.
# Der Text kann hier nur stehen, da eine Raute am Anfang der Zeile steht.
# Dadurch werden diese Zeilen nicht ausgeführt.
5+3
# In diesen Zellen wird der Python Code geschrieben, manchmal müssen Sie ihn schreiben,
# manchmal steht der Code schon dort und muss von Ihnen nur ausgeführt werden.
```
%% Cell type:markdown id: tags:
# Python-Grundlagen
- Dynamisch typisierte Sprache
- Statt geschweifter Klammern für Codeblöcke (Funktionen, Schleifen) wird Code mit vier Leerzeichen (pro Hierarchieebene) eingerückt
- Die meisten Editoren ersetzen Tab automatisch durch vier Leerzeichen
- Kommentare beginnen mit Raute #
%% Cell type:markdown id: tags:
## Grundlegende Datentypen
Zahlentypen (int/float) sind größtenteils äquivalent zu Java. Strings können mit doppelten oder einfachen Anführungszeichen deklariert werden.
%% Cell type:code id: tags:
```
# Variablen definieren
a = 2*2.0
b = 5
# Ausgabe
print(a + b)
# Diese Zelle auswählen und mit `<SHIFT> + <ENTER>` ausführen.
# Der letzte Rückgabewert der Zelle wird dann unten ausgegeben,
# hier also der Wert von `a+b`:b
```
%% Cell type:markdown id: tags:
Die grundlegenden Rechenoperationen __`+`, `-`, `*`, `/`__ und __`**`__ sind ebenfalls in Python verfügbar und verhalten sich, wie man es erwartet:
%% Cell type:code id: tags:
```
# äquivalent zu a = a + 1
a += 1
print(a)
```
%% Cell type:code id: tags:
```
# Potenzieren
2**4
```
%% Cell type:code id: tags:
```
# Division
2/4
```
%% Cell type:markdown id: tags:
Es gibt verschiedene Variablentypen:
- int (Ganzzahl, z.B. 1, 20, 52432432)
- float (Gleitkommazahl, z.B. 1.423, 1/3, 0.23487235723)
- str (Zeichenkette, z.B. "Hello World", 'this is a string')
- bool (Wahrheitswerte, z.B. True, False)
%% Cell type:code id: tags:
```
# Zeichenketten bzw. strings
text1 = 'Hallo '
text2 = "Welt"
print (text1 + text2)
# Andere Datentypen müssen explizit in Strings konvertiert werden,
# wenn sie an einen String angehängt werden sollen.
print(text1 + str(1))
# oder man muss sie durch Kommata trennen:
print(text1,1)
```
%% Cell type:code id: tags:
```
# Zeichenkette zu float
float('1')
```
%% Cell type:code id: tags:
```
# integer zu float
float(1)
```
%% Cell type:markdown id: tags:
*None* entspricht *null* in Java.
%% Cell type:code id: tags:
```
myvar = None
```
%% Cell type:code id: tags:
```
print(myvar)
```
%% Cell type:code id: tags:
```
if myvar is None:
print('x ist nicht definiert')
```
%% Cell type:markdown id: tags:
## Listen
Listen werden mit eckigen Klammern oder list() initialisiert.
%% Cell type:code id: tags:
```
l = [1,2,3,3]
l.append(4)
print(l)
```
%% Cell type:markdown id: tags:
Vorsicht bei der Kombination von Listen. append hängt die übergebene Variable als einzelnen Listeneintrag an die Liste an.
%% Cell type:code id: tags:
```
l.append([5, 6])
print(l)
```
%% Cell type:markdown id: tags:
Zur Kombination von zwei Listen wird der +-Operator verwendet.
%% Cell type:code id: tags:
```
l2 = l + [5,6]
print(l2)
```
%% Cell type:markdown id: tags:
## Mengen
Mengen können mit geschweiften Klammern oder set() initialisiert werden.
%% Cell type:code id: tags:
```
s = {1,2,3,3}
s2 = set([2,3,4,5])
print(s)
print(s.intersection(s2))
```
%% Cell type:code id: tags:
```
s.add(9)
s.remove(2)
s
```
%% Cell type:markdown id: tags:
Mit list() und set() können die Typen auch ineinander konvertiert werden.
%% Cell type:code id: tags:
```
list(s)
```
%% Cell type:code id: tags:
```
set([1,2,3])
```
%% Cell type:markdown id: tags:
## Ranges
Auflistung von Zahlen, werden z.Bsp. für for-Schleifen mit Index verwendet.
%% Cell type:code id: tags:
```
for i in range(5):
print(i)
```
%% Cell type:markdown id: tags:
## Tupel
Für sortierete Werte mit fester Komponentenanzahl und fester Bedeutung für jeden Eintrag.
%% Cell type:code id: tags:
```
essen = 'Chili'
preis = 2.51
boneintrag = (essen, preis)
print(boneintrag)
print(boneintrag[0])
print(boneintrag[1])
```
%% Cell type:code id: tags:
```
(essen2, preis2) = boneintrag
print(essen2)
print(preis2)
```
%% Cell type:markdown id: tags:
Klammern können oft weggelassen werden
%% Cell type:code id: tags:
```
boneintrag = essen, preis
essen2, preis2 = boneintrag
print(boneintrag)
print(essen2)
print(preis2)
```
%% Cell type:markdown id: tags:
## Dictionaries
Äquivalent zu Maps.
%% Cell type:code id: tags:
```
d = {'Chili': 1.90, 'Penne': 2.50}
```
%% Cell type:code id: tags:
```
d.keys()
```
%% Cell type:code id: tags:
```
d.values()
```
%% Cell type:code id: tags:
```
for key, val in d.items():
print('{}: {}'.format(key, val))
```
%% Cell type:code id: tags:
```
d['Chili']
```
%% Cell type:code id: tags:
```
d['Burger'] = 4.90
d
```
%% Cell type:code id: tags:
```
del d['Burger']
d
```
%% Cell type:markdown id: tags:
## If-Anweisungen
%% Cell type:code id: tags:
```
if 2>1 or 1>2:
print ('Bedingung erfüllt.')
```
%% Cell type:code id: tags:
```
y = 10
x = 5 if y > 10 else 4
print(x)
```
%% Cell type:markdown id: tags:
## Schleifen
%% Cell type:code id: tags:
```
x = 5
while x > 0:
x -= 1
x
```
%% Cell type:code id: tags:
```
for x in ['a', 'b', 'c']:
print(x)
```
%% Cell type:markdown id: tags:
## Funktionen
%% Cell type:code id: tags:
```
def sum_upto(n):
return n*(n+1)/2
sum_upto(4)
```
%% Cell type:markdown id: tags:
Zur besseren Übersicht (insbesondere bei vielen Parametern) können diese auch namentlich zugewiesen werden.
%% Cell type:code id: tags:
```
sum_upto(n=4)
```
%% Cell type:markdown id: tags:
Funktionen können *Default-Parameter* haben, d.h. Werte, die von der Funktion als Standardwert verwendet werden (wenn kein anderer Wert übergeben wird). Default-Parameter müssen am Ende der Funktion stehen und übergeben werden.
%% Cell type:code id: tags:
```
def fun_with_default(x=3):
print('Parameter is {}'.format(x))
```
%% Cell type:code id: tags:
```
fun_with_default()
```
%% Cell type:code id: tags:
```
fun_with_default(x=4)
```
%% Cell type:markdown id: tags:
Funktionen können wie Variablen referenziert werden (Pointer auf die Funktion) und zum Beispiel als Parameter übergeben werden.
%% Cell type:code id: tags:
```
def calc_and_print(calc_function, n):
calc_result = calc_function(n)
print(calc_result)
```
%% Cell type:code id: tags:
```
calc_and_print(sum_upto, 4)
```
%% Cell type:markdown id: tags:
# <font color='red'>--------------- Praktisch für Python, aber nicht für unseren Kurs -----------------</font>
%% Cell type:markdown id: tags:
## Lambda-Funktionen
I.d.R. für Inline-Funktionen. Können zum Beispiel an Funktionen als Parameter übergeben oder als Variable deklariert werden. Lambdas enthalten ein einzelnes Statement, dessen Wert automatisch der Rückgabewert ist.
%% Cell type:code id: tags:
```
calc_square = lambda x: x**2
calc_square(3)
```
%% Cell type:code id: tags:
```
calc_and_print(calc_square, 4)
```
%% Cell type:code id: tags:
```
calc_and_print(lambda x: x**3, 4)
```
%% Cell type:markdown id: tags:
## List Comprehensions
%% Cell type:code id: tags:
```
y = [x**2 for x in range(10)]
y
```
%% Cell type:code id: tags:
```
xy = [(x, x**2) for x in range(10) if x%2 == 0]
xy
```
%% Cell type:markdown id: tags:
## Klassen
Objekte einer Klasse bekommen bei Methodenaufrufen als ersten Parameter automatisch das *"self"*-Objekt übergeben (vgl. *this* in Java). Dieser Parameter muss also immer auch als erster Parameter einer Klassenmethode übergeben werden.
%% Cell type:code id: tags:
```
class Vehicle():
# Constructor
def __init__(self, n_wheels=4, noise='beep'):
self.n_wheels = n_wheels
self.noise = noise
def make_noise(self):
print(self.noise)
```
%% Cell type:code id: tags:
```
basicVehicle = Vehicle()
basicVehicle.make_noise()
```
%% Cell type:markdown id: tags:
Properties sind immer von außen sichtbar und lassen sich verändern. Properties, die nicht zur Veränderung gedacht sind, werden nach Konvention durch zwei Unterstriche im Namen gekennzeichnet.
%% Cell type:code id: tags:
```
basicVehicle.n_wheels
```
%% Cell type:markdown id: tags:
Vererbung ist in Python möglich. In der Regel wird aber Duck-Typing verwendet.
“When I see a bird that walks like a duck and swims like a duck and quacks like a duck, I call that bird a duck.”
%% Cell type:code id: tags:
```
bike = Vehicle(n_wheels=2, noise='ring')
bike.make_noise()
```
%% Cell type:code id: tags:
```
class Bike(Vehicle):
def __init__(self):
self.n_wheels = 2
self.noise = 'ring'
```
%% Cell type:code id: tags:
```
Bike().make_noise()
```
%% Cell type:markdown id: tags:
![CC-BY-NC](https://scm.cms.hu-berlin.de/ibi/python/-/raw/master/img/cc-by-nc.png)
Dieses Notebook ist als freies Werk unter der Lizenz [Creative Commons Attribution-NonCommercial 3.0 Unported](http://creativecommons.org/licenses/by-nc/3.0/) verfügbar. Sie dürfen die Inhalte kopieren, verteilen und verändern, solange Sie die Urheber nennen und sie nicht für kommerzielle Zwecke nutzen.
......
This diff is collapsed.
%% Cell type:markdown id: tags:
# 12. Übungsblatt
Mit diesem Python-Code können Sie Ihren regulären Ausdruck testen:
%% Cell type:code id: tags:
```
import re
"""
Ändern Sie den folgenden regulären Ausdruck, so dass alle
positiven Muster erkannt werden, aber kein negatives Muster.
"""
muster = re.compile("Z")
positive = [
"rap them",
"tapeth",
"apth",
"wrap/try",
"sap tray",
"87ap9th",
"apothecary"
]
negative = [
"aleht",
"happy them",
"tarpth",
"Apt",
"peth",
"tarreth",
"ddapdg",
"apples",
"shape the"
]
# testen, ob alle positiven Muster richtig erkannt werden
positive_not_matched = [s for s in positive if not muster.findall(s)]
if positive_not_matched:
print("Folgende positiven Muster wurden nicht erkannt:", ", ".join(positive_not_matched))
# testen, ob keine negativen Muster erkannt werden
negative_matched = [s for s in negative if muster.findall(s)]
if negative_matched:
print("Folgende negativen Muster wurden erkannt:", ", ".join(negative_matched))
if not positive_not_matched and not negative_matched:
print("Herzlichen Glückwunsch, Sie haben das richtige Muster gefunden!")
```
%% Cell type:markdown id: tags:
Nachfolgend noch einige Beispiele zur Verwendung von regulären Ausdrücke mit Python:
%% Cell type:code id: tags:
```
# Funktionen für reguläre Ausdrücke werden im Modul "re" bereitgestellt
import re
# die Methode "findall" findet alle Teilzeichenketten in einer Zeichenkette,
# die auf das angegebene Muster passen
re.findall("cat|dog", "This sentence contains a dog.")
```
%% Cell type:code id: tags:
```
# die Methode "match" testet, ob die gesamte Zeichenkette auf das angegebene Muster passt
re.match(".*dog\\.", "This sentence contains a dog.")
```
%% Cell type:code id: tags:
```
re.match(".*(cat|dog)", "This sentence contains a cat.")
```
%% Cell type:markdown id: tags:
Mit "match" können wir beispielsweise unsere Ergebnisse für Aufgabe 1 prüfen:
%% Cell type:code id: tags:
```
if re.match("[hc]?at", "cat"):
print("Wort wurde erkannt")
else:
print("Wort wurde nicht erkannt")
```
%% Cell type:markdown id: tags:
%% Cell type:code id: tags:
```
# Es gibt eine umfangreiche eingebaute Hilfe:
help(re)
```
%% Cell type:code id: tags:
```
```
%% Cell type:markdown id: tags:
![CC-BY-NC](https://scm.cms.hu-berlin.de/ibi/python/-/raw/master/img/cc-by-nc.png)
Dieses Notebook ist als freies Werk unter der Lizenz [Creative Commons Attribution-NonCommercial 3.0 Unported](http://creativecommons.org/licenses/by-nc/3.0/) verfügbar. Sie dürfen die Inhalte kopieren, verteilen und verändern, solange Sie die Urheber nennen und sie nicht für kommerzielle Zwecke nutzen.
......
This diff is collapsed.
This diff is collapsed.
%% Cell type:markdown id:divine-arthur tags:
# Code kommentieren
<br/>
<br/>
Dieses Notebook finden Sie hier: https://scm.cms.hu-berlin.de/ibi/python/-/blob/master/programmierspass/Kommentare.ipynb
<br/>
![CC-BY-NC](https://scm.cms.hu-berlin.de/ibi/python/-/raw/master/img/cc-by-nc.png)
Dieses Notebook ist als freies Werk unter der Lizenz [Creative Commons Attribution-NonCommercial 3.0 Unported](http://creativecommons.org/licenses/by-nc/3.0/) verfügbar. Sie dürfen die Inhalte kopieren, verteilen und verändern, solange Sie die Urheber nennen und sie nicht für kommerzielle Zwecke nutzen.
%% Cell type:markdown id:6d80e4a5 tags:
## Agenda
1. Kommentare: was, wie, warum?
2. Zweck von Kommentaren
3. *Anleitung zum Unglücklichsein* oder *How to write unmaintainable code*
4. Aufgaben
5. Literatur
%% Cell type:markdown id:optimum-command tags:
## Kommentare: was, wie, warum?
%% Cell type:markdown id:scientific-convertible tags:
### Was?
- Erklärung oder Anmerkung im Quellcode
- unterstützen Verständlichkeit für Menschen
- Compiler/Interpreter ignorieren diese i.d.R.
```python
#
# traverses a directory and collects title names
#
def traverse(directory, titles):
...
```
%% Cell type:markdown id:competitive-emission tags:
### Wie? → (Python-)Syntax
#### Zeilenkommentare
```python
# am Zeilenanfang
print("Hello World!") # am Ende einer Zeile
```
#### Blockkommentare
```python
def dothis():
"""Als Beschreibung einer Funktion."""
pass
```
%% Cell type:markdown id:oriental-breeding tags:
### Warum Code kommentieren?
> Good code is its own best documentation. ([Steve McConnell](http://en.wikipedia.org/wiki/Steve_McConnell))
> Code is far better describing what code does than English, so just write clear code. ([Mike Grouchy](https://mikegrouchy.com/blog/yes-your-code-does-need-comments))
- viele widersprüchliche Meinungen, z.B.
- möglichst selbsterklärender Code ("self-documenting") mit wenigen Kommentaren
- ausführliche Kommentare und Erklärungen
- wichtig:
- Kommentare müssen korrekt sein und zum Code passen
- überflüssige oder nicht hilfreiche Kommentare vermeiden
- Zielgruppe beachten!
%% Cell type:markdown id:vulnerable-congress tags:
```java
String s = "Wikipedia"; /* Assigns the value "Wikipedia" to the variable s. */
```
→ als Einführungstext für Anfänger*innen ok, sonst überflüssig
%% Cell type:markdown id:b9833c6f tags:
### Aufgabe
1. Welche Software, die Sie kennen oder nutzen, ist Freie Software und daher im Quellcode online verfügbar?
2. Finden Sie den Quellcode dieser (oder ggf. einer anderen) Software (idealerweise in [Versionsverwaltungen](https://en.wikipedia.org/wiki/Version_control) wie GitHub oder GitLab).
3. Suchen Sie im Quellcode nach Kommentaren und finden Sie mindestens einen Block- und einen Zeilenkommentar.
4. Versuchen Sie interessante, lustige, kryptische oder sonstwie für Sie bemerkenswerte Kommentare zu finden.
%% Cell type:markdown id:competitive-binding tags:
## Zweck von Kommentaren
%% Cell type:markdown id:private-vulnerability tags:
### Code planen und prüfen
%% Cell type:code id:violent-montana tags:
```
# alle Einträge rückwärts (chronologisch!) durchlaufen
for eintrag in reversed(logbuch):
# Eintrag verarbeiten
update(eintrag)
```
%% Cell type:markdown id:insured-bronze tags:
- vor dem Programmieren in einer Art Pseudocode den zu schreibenden Code skizzieren
- sollte den Sinn des Codes beschreiben, nicht den Code selbst
- ermöglicht Begutachtung/Prüfung des fertigen Codes → erfüllt dieser seine Aufgabe?
%% Cell type:markdown id:roman-astrology tags:
## Code beschreiben
> Don't document bad code – rewrite it. ([The Elements of Programming Style](https://en.wikipedia.org/wiki/The_Elements_of_Programming_Style_(book)), Kernighan & Plauger)
> Good comments don't repeat the code or explain it. They clarify its intent. Comments should explain, at a higher level of abstraction than the code, what you're trying to do. ([Code Complete](https://en.wikipedia.org/wiki/Code_Complete), McConnell)
%% Cell type:markdown id:deluxe-replica tags:
```python
"status" : d["status"] # unused but required by standard
```
%% Cell type:code id:practical-appointment tags:
```
# Wir benötigen eine stabile Sortierung. Geschwindigkeit spielt keine Rolle.
insertion_sort(liste)
```
%% Cell type:markdown id:moderate-forwarding tags:
- Code zusammenfassen oder Absicht erklären
- NICHT: Code in natürlicher Sprache wiederholen
- auch: (Ursache für) Besonderheiten erklären
- auch: Algorithmus beschreiben
%% Cell type:markdown id:black-constraint tags:
## Einbettung von Ressourcen
%% Cell type:code id:eight-confidentiality tags:
```
# Graph:
#
# 5
# / \
# 3---4
# |\ /|
# | X |
# |/ \|
# 1---2
#
# Adjazenzliste:
nikolaus = {
1: [2, 3, 4],
2: [1, 3, 4],
3: [1, 2, 4, 5],
4: [1, 2, 3, 5],
5: [3, 4]
}
```
%% Cell type:markdown id:extraordinary-gamma tags:
- Diagramme, Flussdiagramme, Tabellen, etc.
%% Cell type:markdown id:dietary-minimum tags:
## Metadaten
%% Cell type:code id:hundred-gazette tags:
```
#
# Process (extract, filter, merge) Vossantos in an org mode file.
#
# Usage: Without any arguments, extracts all Vossanto canidates from
# the given org file.
#
# Author: rja
#
# Changes:
# 2019-12-18 (rja)
# - added field sourceImageLicense
# 2019-12-16 (rja)
# - added option "--images" to enrich URLs for Wikipedia Commons images
# ...
```
%% Cell type:markdown id:southwest-paper tags:
- Namen der Autor*innen, Versionshinweise, Lizenzangaben, Link zur Dokumentation, etc.
- Hinweise zur Nutzung, zu Fehlern/Verbesserungsmöglichkeiten, zum Melden von Fehlern, etc.
%% Cell type:markdown id:initial-links tags:
## Debugging
%% Cell type:code id:atlantic-programming tags:
```
def get_matching_item(bibentry, items):
# heuristic: rely on Crossref's ranking and take the first item
item = items[0]
# heuristic: do (almost) exact string matching on the title (only)
if item.get("title")[0].casefold() == bibentry["title"].casefold():
return item
# debug output
# print(bibentry["ID"], bibentry["title"])
# print(" best Crossref match:", item.get("title"), item.get("DOI"))
return None
```
%% Cell type:markdown id:muslim-adams tags:
- auskommentierter Code wird nicht ausgeführt
- Fehlersuche; "alten" oder alternativen Code deaktivieren
%% Cell type:markdown id:explicit-absolute tags:
## Automatische Erzeugung von Dokumentation
Quelle: https://scikit-learn.org/stable/modules/generated/sklearn.metrics.roc_curve.html
%% Cell type:code id:floating-venezuela tags:
```
def roc_curve(y_true, y_score, *, pos_label=None, sample_weight=None,
drop_intermediate=True):
"""Compute Receiver operating characteristic (ROC)
Note: this implementation is restricted to the binary classification task.
Read more in the :ref:`User Guide <roc_metrics>`.
Parameters
----------
y_true : array, shape = [n_samples]
True binary labels. If labels are not either {-1, 1} or {0, 1}, then
pos_label should be explicitly given.
y_score : array, shape = [n_samples]
Target scores, can either be probability estimates of the positive
class, confidence values, or non-thresholded measure of decisions
(as returned by "decision_function" on some classifiers).
pos_label : int or str, default=None
The label of the positive class.
When ``pos_label=None``, if y_true is in {-1, 1} or {0, 1},
``pos_label`` is set to 1, otherwise an error will be raised.
sample_weight : array-like of shape (n_samples,), default=None
Sample weights.
drop_intermediate : boolean, optional (default=True)
Whether to drop some suboptimal thresholds which would not appear
on a plotted ROC curve. This is useful in order to create lighter
ROC curves.
.. versionadded:: 0.17
parameter *drop_intermediate*.
Returns
-------
fpr : array, shape = [>2]
Increasing false positive rates such that element i is the false
positive rate of predictions with score >= thresholds[i].
tpr : array, shape = [>2]
Increasing true positive rates such that element i is the true
positive rate of predictions with score >= thresholds[i].
thresholds : array, shape = [n_thresholds]
Decreasing thresholds on the decision function used to compute
fpr and tpr. `thresholds[0]` represents no instances being predicted
and is arbitrarily set to `max(y_score) + 1`.
See also
--------
roc_auc_score : Compute the area under the ROC curve
Notes
-----
Since the thresholds are sorted from low to high values, they
are reversed upon returning them to ensure they correspond to both ``fpr``
and ``tpr``, which are sorted in reversed order during their calculation.
References
----------
.. [1] `Wikipedia entry for the Receiver operating characteristic
<https://en.wikipedia.org/wiki/Receiver_operating_characteristic>`_
.. [2] Fawcett T. An introduction to ROC analysis[J]. Pattern Recognition
Letters, 2006, 27(8):861-874.
Examples
--------
>>> import numpy as np
>>> from sklearn import metrics
>>> y = np.array([1, 1, 2, 2])
>>> scores = np.array([0.1, 0.4, 0.35, 0.8])
>>> fpr, tpr, thresholds = metrics.roc_curve(y, scores, pos_label=2)
>>> fpr
array([0. , 0. , 0.5, 0.5, 1. ])
>>> tpr
array([0. , 0.5, 0.5, 1. , 1. ])
>>> thresholds
array([1.8 , 0.8 , 0.4 , 0.35, 0.1 ])
"""
```
%% Cell type:markdown id:alien-protocol tags:
## Anweisungen für bestimmte Programme
%% Cell type:code id:dominant-mongolia tags:
```
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4
print("Testing")
```
%% Cell type:markdown id:strange-effects tags:
- "Shebang" (#!) → gibt den zu verwendenden Interpreter an
- "Magic comments", z.B. zur verwendeten Codierung
- ... oder zur Konfiguration des Editors
%% Cell type:markdown id:destroyed-angle tags:
## Stressabbau :-)
%% Cell type:markdown id:blocked-conjunction tags:
```c
/*
* Some dipshit decided to store some other bit of information
* in the high byte of the file length. Truncate size in case
* this CDROM was mounted with the cruft option.
*/
```
Quelle: https://github.com/torvalds/linux/blob/master/fs/isofs/inode.c#L1396
[Linux Swear Count](http://www.vidarholen.net/contents/wordcount/)
%% Cell type:markdown id:commercial-mauritius tags:
```c
//
// Dear maintainer:
//
// Once you are done trying to 'optimize' this routine,
// and have realized what a terrible mistake that was,
// please increment the following counter as a warning
// to the next guy:
//
// total_hours_wasted_here = 42
//
```
Quelle: https://stackoverflow.com/questions/184618/what-is-the-best-comment-in-source-code-you-have-ever-encountered
%% Cell type:markdown id:shaped-finder tags:
## Beispiele
- https://borgelt.net/bin/apriori (→ apriori.c)
- https://github.com/zedshaw/lamson/blob/master/lamson/server.py#L55
- https://github.com/weltliteratur/vossanto/blob/master/org.py
- https://scm.cms.hu-berlin.de/ibi/notebooks/-/blob/master/Mondrian.ipynb
%% Cell type:markdown id:directed-lithuania tags:
## *Anleitung zum Unglücklichsein* oder *How to write unmaintainable code*
> Any fool can tell the truth, but it requires a man of some sense to know how to lie well. ([Samuel Butler](https://en.wikipedia.org/wiki/Samuel_Butler_%28novelist%29) (1835 - 1902))
> Incorrect documentation is often worse than no documentation. ([Bertrand Meyer](https://en.wikipedia.org/wiki/Bertrand_Meyer))
Since the computer ignores comments and documentation, you can lie outrageously and do everything in your power to befuddle the poor maintenance programmer.
Quelle: Roedy Green, [How To Write Unmaintainable Code](https://web.archive.org/web/20120306115925/http://freeworld.thc.org/root/phun/unmaintain.html) ([Originalseite](https://www.mindprod.com/jgloss/unmain.html))
%% Cell type:markdown id:unusual-excellence tags:
### Lie in the comments
You don't have to actively lie, just fail to keep comments as up to date with the code.
%% Cell type:code id:obvious-romantic tags:
```
# remove control characters
def rm_ctrl(text):
return re.sub(r"[\n\t\r]+", " ", text).strip()
```
%% Cell type:markdown id:attempted-mount tags:
### Document the obvious
Pepper the code with comments like `/* add 1 to i */` however, never document wooly stuff like the overall purpose of the package or method.
%% Cell type:code id:latter-north tags:
```
def einefunktion(a, b):
# a² zu b² addieren
c = a**2 + b**2
# die Wurzel des Ergebnisses zurückgeben
return math.sqrt(c)
```
%% Cell type:code id:hydraulic-yeast tags:
```
def einefunktion(a, b):
# Für zwei gegebene Seitenlängen a und b die dritte Seitenlänge
# c eines rechtwinkligen Dreiecks mit Hilfe des Satzes des
# Pythagoras (a² + b² = c²) berechnen.
c = a**2 + b**2
return math.sqrt(c)
```
%% Cell type:markdown id:ahead-sheep tags:
### Document How Not Why
Document only the details of what a program does, not what it is attempting to accomplish. That way, if there is a bug, the fixer will have no clue what the code should be doing.
%% Cell type:code id:round-warning tags:
```
def read_dict(lines):
d = dict()
for line in lines:
if not line.startswith('#'):
# nur Zeilen ohne # am Anfang verarbeiten
key, val = line.strip().split('\t', 1)
d[key] = val
return d
```
%% Cell type:markdown id:still-marketplace tags:
### Avoid Documenting the "Obvious"
If, for example, you were writing an airline reservation system, make sure there are at least 25 places in the code that need to be modified if you were to add another airline. Never document where they are. People who come after you have no business modifying your code without thoroughly understanding every line of it.
%% Cell type:code id:frequent-uganda tags:
```
sep = '\t' # column separator
def print_csv(parts):
for part in parts:
print(sep.join([part_to_string(part[p]) for p in part]))
def read_dict(lines):
d = dict()
for line in lines:
if not line.startswith('#'):
key, val = line.strip().split('\t', 1)
d[key] = val
return d
```
%% Cell type:markdown id:interracial-translator tags:
### On the Proper Use Of Documentation Templates
Consider function documentation prototypes used to allow automated documentation of the code. These prototypes should be copied from one function (or method or class) to another, but never fill in the fields. If for some reason you are forced to fill in the fields make sure that all parameters are named the same for all functions, and all cautions are the same but of course not related to the current function at all.
%% Cell type:markdown id:statistical-evening tags:
```java
/**
* @param receiver
* @param limit
* @param offset
* @param session
*
* @return a lists of posts of type R with the inbox content
*/
public List<Post<R>> getPostsFromInbox(final String receiver, final int limit, final int offset, final DBSession session) {
...
}
/**
* TODO: improve docs
*
* @param days
* @param limit
* @param offset
* @param hashId
* @param session
*
* @return list of posts
*/
public List<Post<R>> getPostsPopular(final int days, final int limit, final int offset, final HashID hashId, final DBSession session) {
...
}
```
%% Cell type:markdown id:charged-conviction tags:
### On the Proper Use of Design Documents
When implementing a very complicated algorithm, use the classic software engineering principles of doing a sound design before beginning coding. Write an extremely detailed design document that describes each step in a very complicated algorithm. The more detailed this document is, the better.
In fact, the design doc should break the algorithm down into a hierarchy of structured steps, described in a hierarchy of auto-numbered individual paragraphs in the document. Use headings at least 5 deep. Make sure that when you are done, you have broken the structure down so completely that there are over 500 such auto-numbered paragraphs. For example, one paragraph might be (this is a real example)
> 1.2.4.6.3.13 - Display all impacts for activity where selected mitigations can apply (short pseudocode omitted).
**then ...** (and this is the kicker) when you write the code, for each of these paragraphs you write a corresponding global function named:
```python
Act1_2_4_6_3_13()
```
Do not document these functions. After all, that's what the design document is for!
Since the design doc is auto-numbered, it will be extremely difficult to keep it up to date with changes in the code (because the function names, of course, are static, not auto-numbered.) This isn't a problem for you because you will not try to keep the document up to date. In fact, do everything you can to destroy all traces of the document.
Those who come after you should only be able to find one or two contradictory, early drafts of the design document hidden on some dusty shelving in the back room near the dead 286 computers.
%% Cell type:markdown id:rolled-starter tags:
### Units of Measure
Never document the units of measure of any variable, input, output or parameter, e.g., feet, metres, cartons. This is not so important in bean counting, but it is very important in engineering work. As a corollary, never document the units of measure of any conversion constants, or how the values were derived. It is mild cheating, but very effective, to salt the code with some incorrect units of measure in the comments. If you are feeling particularly malicious, make up your **own** unit of measure; name it after yourself or some obscure person and never define it. If somebody challenges you, tell them you did so that you could use integer rather than floating point arithmetic.
%% Cell type:code id:super-mounting tags:
```
def wurfdistanz(geschwindigkeit, winkel):
return geschwindigkeit**2 / 9.81 * math.sin(2*winkel)
```
%% Cell type:markdown id:eligible-graduate tags:
### Gotchas
Never document gotchas in the code. If you suspect there may be a bug in a class, keep it to yourself. If you have ideas about how the code should be reorganised or rewritten, for heaven's sake, do not write them down. Remember the words of Thumper in the movie Bambi "*If you can't say anything nice, don't say anything at all*". What if the programmer who wrote that code saw your comments? What if the owner of the company saw them? What if a customer did? You could get yourself fired. An anonymous comment that says "This needs to be fixed!" can do wonders, especially if it's not clear what the comment refers to. Keep it vague, and nobody will feel personally criticised.
%% Cell type:code id:electric-yesterday tags:
```
print(key, ":", value) # FIXME
```
%% Cell type:code id:legendary-fruit tags:
```
print(key, ":", value) # FIXME: ignore keys with empty values
```
%% Cell type:markdown id:incident-queue tags:
### Documenting Variables
Never put a comment on a variable declaration. Facts about how the variable is used, its bounds, its legal values, its implied/displayed number of decimal points, its units of measure, its display format, its data entry rules (e.g. total fill, must enter), when its value can be trusted etc. should be gleaned from the procedural code. If your boss forces you to write comments, lard method bodies with them, but never comment a variable declaration, not even a temporary!
%% Cell type:markdown id:competitive-budapest tags:
```c
const char *name;
int len;
char c;
unsigned long hash;
```
%% Cell type:markdown id:popular-bracelet tags:
### Disparage In the Comments
Discourage any attempt to use external maintenance contractors by peppering your code with insulting references to other leading software companies, especial anyone who might be contracted to do the work, e.g.:
```java
/* The optimised inner loop.
This stuff is too clever for the dullard at Software Services Inc., who would
probably use 50 times as memory & time using the dumb routines in <math.h>.
*/
class clever_SSInc
{
...
}
```
If possible, put insulting stuff in syntactically significant parts of the code, as well as just the comments so that management will probably break the code if they try to sanitise it before sending it out for maintenance.
%% Cell type:markdown id:human-thomson tags:
### COMMENT AS IF IT WERE CØBØL ON PUNCH CARDS
Always refuse to accept advances in the development environment arena, especially SCIDs. Disbelieve rumors that all function and variable declarations are never more than one click away and always assume that code developed in Visual Studio 6.0 will be maintained by someone using edlin or vi. Insist on Draconian commenting rules to bury the source code proper.
→ https://www.mainframestechhelp.com/tutorials/cobol/reference-format.htm
%% Cell type:markdown id:laden-glance tags:
```cobol
000100 IDENTIFICATION DIVISION. 000100
000200 PROGRAM-ID. HELLO. 000101
000300 AUTHOR. JavaTpoint 000102
000400* THIS IS A COMMENT LINE 000103
000500 PROCEDURE DIVISION. 000104
000600 A000-FIRST-PARA. 000105
000700/ First Para Begins - Documentation Purpose 000106
000800 DISPLAY "Comments". 000107
000900 STOP RUN. 000108
```
Quelle: https://www.javatpoint.com/cobol-coding-sheet
%% Cell type:markdown id:unusual-dairy tags:
### Monty Python Comments
On a method called makeSnafucated insert only the JavaDoc `/* make snafucated */`. Never define what *snafucated* means **anywhere**. Only a fool does not already know, with complete certainty, what *snafucated* means. For classic examples of this technique, consult the Sun AWT JavaDOC.
```java
/* make snafucated */
void makeSnafucated() {
...
}
```
%% Cell type:markdown id:opposed-score tags:
## Aufgaben
%% Cell type:markdown id:protecting-cleaners tags:
### Kommentare beschreiben
Suchen Sie nach Quellcode auf Ihrem Rechner oder im Web und lesen Sie die Kommentare im Code.
1. Welche *Arten von Kommentaren* können Sie finden?
2. Was ist der *Zweck* der Kommentare?
Suchen Sie so lange, bis Sie jeweils zwei Varianten gefunden haben.
%% Cell type:markdown id:human-redhead tags:
### Code selber kommentieren
Fügen Sie Kommentare zu den folgenden Codebeispielen hinzu. Überlegen Sie sich für jeden Kommentar,
- welchen *Zweck* Sie mit dem Kommentar erreichen wollen,
- welche *Art* von Kommentar Sie verwenden wollen und
- welche *Zielgruppe(n)* Sie damit ansprechen wollen.
%% Cell type:code id:hearing-castle tags:
```
def boxsay(s, h="-", v="|", c="+"):
print(c + (2+len(str(s)))*h + c)
print(v, str(s), v)
print(c + (2+len(str(s)))*h + c)
boxsay("Hallo Welt!")
```
%% Cell type:code id:tired-stanley tags:
```
def equal_chars(v, w):
m = []
for i in range(min(len(v), len(w))):
if v[i] == w[i]:
m.append(v[i])
else:
m.append("_")
return m
equal_chars("Magdeburg", "Hannover")
```
%% Cell type:code id:structured-butter tags:
```
import urllib.request
import re
with urllib.request.urlopen("https://de.wikipedia.org/wiki/IP-Adresse") as f:
html = f.read().decode('utf8')
for ip in sorted(re.findall("[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+", html)):
print(ip)
```
%% Cell type:code id:solved-andrews tags:
```
import json
def chars_markdown(fname, celltype):
with open(fname) as json_file:
data = json.load(json_file)
count = 0
for cell in data['cells']:
if cell['cell_type'] == celltype:
for line in cell['source']:
count += len(line.strip().replace(" ", ""))
return count
chars_markdown("Kommentare.ipynb", "code")
```
%% Cell type:code id:wireless-importance tags:
```
from urllib import request
import json
def get_dracor(corpus, play=None):
url = "https://dracor.org/api/corpora/" + corpus
if play is not None:
url = url + "/play/" + play + "/spoken-text"
with request.urlopen(url) as req:
text = req.read().decode()
if play is None:
return json.loads(text)
return text
get_dracor("ger")["description"]
```
%% Cell type:code id:animated-straight tags:
```
from collections import Counter
import re
re_word = re.compile("\W")
def count_terms(text):
nouns = Counter()
upper = Counter()
tokens = text.split(' ')
for i, term in enumerate(tokens):
if len(term) > 0 and term[0].isupper():
if i > 0 and len(tokens[i-1]) > 0 and tokens[i-1][-1] not in ['.', '?', '!', ':']:
term = re_word.sub("", term)
nouns[term] += 1
if term.isupper():
term = re_word.sub("", term)
if len(term) > 1:
upper[term] += 1
return nouns, upper
count_terms("Die Europäische Union hat Beobachterstatus in der G7, ist Mitglied in der G20 und vertritt ihre Mitgliedstaaten in der Welthandelsorganisation.")
```
%% Cell type:code id:automotive-writer tags:
```
import numpy as np
import matplotlib.pyplot as plt
k = 50 # number of horizontal points
n = 80 # number of vertical lines
plt.rcParams['figure.figsize'] = (15, 15)
plt.rcParams['figure.dpi'] = 140
plt.style.use('dark_background')
plt.axis('off')
plt.xlim(-100, 200)
plt.ylim(-60, 240)
xs = np.linspace(0, 100, k)
def sq(x, minx, maxx, miny, maxy, invert=False):
x = (x - minx) / (maxx - minx)
if invert:
x = 1 - x
if x < 0.5: # ascent
fx = 2*x**2
else: # descent
fx = (1 - 2*(1-x)**2)
return fx * (maxy - miny) + miny
def f(x, left, right, width, height):
if x < left or x > right: # left + right
return np.abs(np.random.normal(0, 0.5))
if x < left + width: # ascent
return np.abs(np.random.normal(0, 1.0)) + sq(x, left, left + width, 0, height)
if x > right - width: # descent
return np.abs(np.random.normal(0, 1.0)) + sq(x, right - width, right, 0, height, True)
else: # middle
return np.random.exponential(2) + height
for i in range(1, n+1):
data = [f(x, 25, 75, 10, 5) + i*2 for x in xs]
plt.plot(xs, data, color="white", zorder=n-i, linewidth=1)
plt.fill_between(xs, data, color="black", zorder=n-i)
plt.show()
```
%% Cell type:markdown id:developed-figure tags:
## Literatur
- https://en.wikipedia.org/wiki/Comment_(computer_programming)
- Keyes, Jessica (2003). Software Engineering Handbook. CRC Press. ISBN 978-0-8493-1479-7.
- Roedy Green, [How To Write Unmaintainable Code](https://web.archive.org/web/20120306115925/http://freeworld.thc.org/root/phun/unmaintain.html) ([Originalseite](https://www.mindprod.com/jgloss/unmain.html))
- https://mikegrouchy.com/blog/yes-your-code-does-need-comments
- https://stackoverflow.com/questions/184618/what-is-the-best-comment-in-source-code-you-have-ever-encountered
......
%% Cell type:markdown id: tags:
# Handling Different File Formats in Python: Loading and Saving
<br/>
<br/>
Dieses Notebook finden Sie hier: https://scm.cms.hu-berlin.de/ibi/python/-/blob/master/programmierspass/Loading_Files.ipynb
<br/>
![CC-BY-NC](https://scm.cms.hu-berlin.de/ibi/python/-/raw/master/img/cc-by-nc.png)
Dieses Notebook ist als freies Werk unter der Lizenz [Creative Commons Attribution-NonCommercial 3.0 Unported](http://creativecommons.org/licenses/by-nc/3.0/) verfügbar. Sie dürfen die Inhalte kopieren, verteilen und verändern, solange Sie die Urheber nennen und sie nicht für kommerzielle Zwecke nutzen.
%% Cell type:markdown id: tags:
## Was ist es und worum geht es?
Zur **Analyse von Daten** ist es wichtig, dass **die Daten zunächst in Python geladen** werden, um sie anschließend verarbeiten zu können. Dies kann entweder aus einer lokalen Datei am PC oder direkt von einer Webseite erfolgen. Die erste Herausforderung besteht darin, dass es **viele verschiedene Dateiformate** gibt, die jeweils ihre eigene Struktur und Darstellung haben und dabei ihre Besonderheiten aufweisen.
In diesem Notebook schauen wir uns an, wie man verschiedene Dateiformate in Python lädt und wieder abspeichert.
Folgende Dateiformate werden abgedeckt:
- csv (Comma-separated values)
- tsv (Tab-separated values)
- json (JavaScript Object Notation)
- html (HyperText Markup Language)
- xls/xlsx (Excel spreadsheets)
- xml (Extensible Markup Language)
- tar/gz (compressed files)
%% Cell type:markdown id: tags:
### CSV (Comma-separated values) und tsv (Tab-separated values)
`csv`- und `tsv`-Dateien sind ähnlich, da sie Textdateien sind, die (in der Regel) strukturierte Daten enthalten, normalerweise in Form von Tabellen. Die Daten sind zeilenweise organisiert, wobei jede Zeile einen separaten Datensatz darstellt, der mehrere Datenfelder enthält, die in Spalten in der Tabelle stehen.
Die Trennung der Datenfelder erfolgt durch ein besonderes `Trennzeichen`, bei `csv`-Dateien ist dies ein Komma (`,`), bei `tsv`-Dateien ein Tab (`\t`). Theoretisch kann man auch ein anderes Trennzeichen verwenden.
Hinweis: In `csv`-Dateien, die Zahlen im deutschen Format enthalten (d.h. die Dezimalstellen werden durch ein Komma getrennt: `100,00` statt `100.00`), ist das Trennzeichen oft ein Semikolon (`;`) und nicht ein Komma.
Beispiel:
| Stadt | Postleitzahl | Fläche (km²) | bev_insg | bev_m | bev_w |
|--------------------------------|--------------|-------------:|---------:|--------:|--------:|
| Berlin - Stadt | 10178 | 891.12 | 3677472 | 1807826 | 1869646 |
| Hamburg - Freie und Hansestadt | 20038 | 755.09 | 1853935 | 907682 | 946253 |
| München - Landeshauptstadt | 80313 | 310.7 | 1487708 | 725594 | 762114 |
| Köln - Stadt | 50667 | 405.01 | 1073096 | 521939 | 551157 |
| Frankfurt am Main - Stadt | 60311 | 248.31 | 759224 | 374525 | 384699 |
%% Cell type:code id: tags:
```
import pandas
# top50_german_cities.csv
# top50_german_cities.tsv
```
%% Cell type:code id: tags:
```
import csv
```
%% Cell type:code id: tags:
```
import tsv
```
%% Cell type:markdown id: tags:
### XLS/XLSX (EXCEL Dateien)
Excel kennt wohl jeder. Keine Einführung notwendig.
%% Cell type:code id: tags:
```
import pandas as pd
# top50_german_cities.xlsx
```
%% Cell type:markdown id: tags:
### JSON (JavaScript Object Notation )
`json`-Dateien sind ein weit verbreitetes Format für den Austausch von Daten im Internet. Sie sind eine Form von Textdateien, die Daten in einem lesbaren Format speichern. `json` steht für JavaScript Object Notation und das Format basiert auf JavaScript-Objekten.
Eine `json`-Datei besteht aus Key-Value-Paaren, die miteinander durch Kommas getrennt sind. Die `keys` sind meist Zeichenketten, die in doppelten Anführungszeichen stehen, und die `values` können verschiedene Datentypen sein, wie Zahlen, Strings, Objekte oder Arrays/Listen.
Das JSON-Format ermöglicht es, Daten einfach zu lesen und zu schreiben und es ist ein Standard für den Datenaustausch in vielen Web-API's.
Beispiel (hash/dictionary/object):
```
{
"Berlin - Stadt": {
"Postleitzahl": 10178,
"Fläche (km²)": 891.12,
"bev_insg": 3677472,
"bev_m": 1807826,
"bev_w": 1869646
},
...
}
```
Beispiel (array/list):
```
[
{
"Stadt": "Berlin - Stadt",
"Postleitzahl": 10178,
"Fläche (km²)": 891.12,
"bev_insg": 3677472,
"bev_m": 1807826,
"bev_w": 1869646
},
...
]
```
%% Cell type:code id: tags:
```
import pandas
# top50_german_cities_array.json
# top50_german_cities_hash.json
```
%% Cell type:code id: tags:
```
import json
```
%% Cell type:markdown id: tags:
### HTML (Hypertext Markup Language)
HTML (Hypertext Markup Language) ist eine Programmiersprache zur Strukturierung von Webseiten.
Wir schauen uns im Folgenden an, wie man sehr einfach Tabellen aus Webseiten in Python laden kann ohne die Tabelle oder die Webseite herunterzuladen und anschließend schauen wir nochmal auf das allgemeine Laden von html Dateien in Python.
1. HTML-Tabellen in Webseiten:
https://de.wikipedia.org/wiki/Liste_der_Gro%C3%9Fst%C3%A4dte_in_Deutschland
%% Cell type:code id: tags:
```
import pandas
# https://de.wikipedia.org/wiki/Liste_der_Gro%C3%9Fst%C3%A4dte_in_Deutschland
```
%% Cell type:markdown id: tags:
2. allgemeine HTML Seiten abrufen und in Python lesen
%% Cell type:code id: tags:
```
import requests
```
%% Cell type:code id: tags:
```
from bs4 import BeautifulSoup
```
%% Cell type:markdown id: tags:
XML (Extensible Markup Language) ist eine Programmiersprache zur Beschreibung und Übertragung von Daten. Eine XML-Datei kann Daten in einer hierarchischen Struktur speichern, in der jedes Element ein anderes Element enthalten kann.
Mit Pandas kann man eine XML-Datei lesen, indem man die Methode read_xml() verwendet. Diese Methode kann eine XML-Datei einlesen und in ein Pandas-DataFrame umwandeln. Man muss allerdings angeben, welches Element als Wurzelelement verwendet werden soll, da die XML-Datei sonst nicht richtig eingelesen werden kann.
%% Cell type:markdown id: tags:
### tar/gz (Archivformate)
Tar/gz Dateien sind Archivformate (genauso wie zum Beispiel .zip), die mehrere Dateien in einer einzigen Datei komprimieren und speichern. Diese Archivformate werden oft verwendet, um Daten effizient zu übertragen oder zu sichern, da sie den Speicherplatz sparen und die Übertragungszeit verkürzen.
%% Cell type:code id: tags:
```
import tarfile
import pandas
# top50_german_cities.tar.gz
with tarfile.open("top50_german_cities.tar.gz", "r:gz") as tar:
members = tar.getmembers()
for member in members:
print(pandas.read_xml(member.name).head(1))
```
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.