Dokumen - Pub Python 3 Module Examples
Dokumen - Pub Python 3 Module Examples
Introduction 1.1
Reading and writing files 1.2
csv - reading and writing CSV files 1.2.1
json - working with JSON files 1.2.2
xml - parsing XML files 1.2.3
zipfile - reading and writing .zip files 1.2.4
Data analysis 1.3
numpy - fast matrix calculations 1.3.1
pandas - comfortable handling of tables 1.3.2
scipy - scientific calculations 1.3.3
scikit-learn - Machine Learning 1.3.4
Data visualisation 1.4
matplotlib - plotting diagrams 1.4.1
pillow - image manipulation 1.4.2
Interacting with the web 1.5
requests - improved retrieving web pages 1.5.1
bs4 - parsing HTML pages 1.5.2
paramiko - executing commands via SSH 1.5.3
Essential standard modules 1.6
math - mathematical functions 1.6.1
os - working with files and directories 1.6.2
random - generating random numbers 1.6.3
re - pattern matching in text 1.6.4
time - working with dates and times 1.6.5
sqlite3 - a simple SQL database 1.6.6
sys - settings of the Python interpreter 1.6.7
itertools - working with lists and generators 1.6.8
Challenges 1.7
Spirale 1.7.1
Postkarte 1.7.2
Thumbnails 1.7.3
Rekursive Grafik 1.7.4
Film 1.7.5
Babynamengenerator 1.7.6
Reguläre Ausdrücke 1.7.7
Google 1.7.8
Webrecherche 1.7.9
Webseite mit Strassennamen 1.7.10
Blog 1.7.11
Python 3 Module Examples
(c) 2016 Dr. Kristian Rother (krother@academis.eu)
The csv module reads and writes nested lists from/to CSV files. You can
set a field delimiter, quote character and line terminator character. Note
that when reading a line, all columns are in string format.
Example
Write a table with two rows to a CSV file:
import csv
["second", 5, 678]]
writer.writerows(data)
outfile.close()
print(row)
Example
Convert a dictionary to a JSON-formatted string:
import json
jj = json.dumps(data)
print(jj)
d = json.loads(jj)
print(d)
The xml module contains several XML parsers. They produce a tree of
DOM objects for each tag that can be searched and allow access to
attributes.
Example
Sample XML data:
<actor_list>
</actor_list>
document = parse('hamlet.xml')
actors = document.getElementsByTagName("actor")
name = act.getAttribute('name')
if node.nodeType == node.TEXT_NODE:
You can add both existing files and strings to a zip file. If you are adding
strings you need to specify the file name it is written to. When you extract
files to a folder, the output folder is automatically created.
Example
Create a new zip archive and add files to it:
import zipfile
z = zipfile.ZipFile('archive.zip', 'w')
z.close()
print(z.namelist())
print(z.extract('test.txt', 'myfolder'))
z.close()
Pre-installed on Anaconda?
yes
Example
Creating a 4 x 2 matrix and adding 10 to each element
import numpy as np
print(vector + 10)
[[10 11 12 13]
[14 15 16 17]]
print(vector.shape)
(2, 4)
import pandas as pd
print(df)
name size
0 Hamlet 1.76
1 Polonius 1.52
2 Ophelia 1.83
3 Claudius 1.95
Sorted lines by name, filter by minimum size, print first two values and
write a CSV file:
sorted = df.sort_values(by='name', ascending=False)
print(tall.head(2))
name size
3 Claudius 1.95
2 Ophelia 1.83
scipy is a Python library for fitting functions and other kinds of numerical
analyses. You find functions for signal processing, Fourier Transform,
generating random datasets and many more. Scipy uses numpy and
matplotlib .
return a * x**2 + b
import numpy as np
y = func(x, 1, 5)
ynoise = y + 20 * np.random.laplace(size=len(x))
fig = plt.figure
plt.savefig('fit.png')
Where to learn more?
http://scipy.org/
scikit-learn
What it is good for?
Machine Learning.
iris = datasets.load_iris()
cross_validation.train_test_split(iris.data, iris.target, \
test_size=0.4, random_state=True)
probability=True).fit(X_train, Y_train)
print(svc.score(X_test, Y_test))
0.983333333333
Do a five-fold cross-validation:
print(accuracy = cross_validation.cross_val_score(svc, X, Y,
cv=5, scoring='accuracy'))
Example
Plot a square function:
from pylab import *
x = list(range(-10, 10))
figure()
title('square function')
xlabel('x')
ylabel('$x^2$')
savefig('plot.png')
Example
Convert all .png images in the directory to half their size.
from PIL import Image
import os
if filename.endswith('.png'):
im = Image.open(filename)
x = im.size[0] // 2
y = im.size[1] // 2
small.save('sm_' + filename)
requests sends HTTP requests to web pages and allows you to read their
content. Most standard tasks are a lot easier compared to the standard
module urllib . requests can sending data to web forms via HTTP
GET and POST, submit files and manage cookies.
Example
Read the homepage of the author.
import requests
r = requests.get('http://www.academis.eu')
print(r.text)
url =
"http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi"
'rettype':'uilist'}
r = requests.get(url, params=param_dict)
print(r.text)
Beautiful soup is much, much easier to use than the default HTML parser
installed with Python.
Example
Parsing list items out of a HTML document:
from bs4 import BeautifulSoup
html = """<html><head></head><body>
<h1>Hamlet</h1>
<ul class="cast">
<li>Hamlet</li>
<li>Polonius</li>
<li>Ophelia</li>
<li>Claudius</li>
</ul>
</body></html"""
for ul in soup.find_all('ul'):
Example
List the directory on a remote machine.
from paramiko import SSHClient
client = SSHClient()
client.load_system_host_keys()
client.connect('ssh.example.com', username="username",
password="password")
WARNING
Do not hard-code your password inside your Python files. Better read it
from a configuration file or environment variable. That way it is less
likely that it gets into wrong hands accidentally
Example
Calculating a square root, a sine, an exponential function and a
logarithm.
import math
print(math.sqrt(49))
print(math.sin(math.pi / 2))
print(math.exp(1.0) == math.e)
print(math.log(256,2))
The os module provides an easy way to interact with files, directories and
other parts of your operating system. It contains many functions to list,
change, copy, remove and examine files and directories.
Example
Change directory and list its contents:
import os
os.chdir('/home/krother/python_modules/')
os.listdir('.')
os.path.exists('os.md')
os.remove('copy.md')
dice = random.randint(1,6)
import random
print random.random()
Generate random numbers from a few
distributions.
import random
random.randint(1,6)
random.random()
random.gauss(0.0, 1.0)
Shuffle a list
data = [1, 2, 3, 4]
random.shuffle(data)
bases = ['A','C','G','T']
print ''.join(dna)
When elements are to be picked without repetition, you would use, the
sample function:
flavors = ['vanilla','banana','mint']
icecream = sample(flavors, 2)
Example
import re
text = "the quick brown fox jumps over the lazy dog"
print(re.findall(".o.", text))
print(re.findall("\s(\wo\w)\s*", text))
['fox', 'dog']
print(re.search('jumps|swims', text))
Online Games
regexone.com/ - Learn regular expressions by simple, interactive
examples. Great place to start.
Regex crossword - Train proper use of single characters, wildcards and
square brackets. Easy.
Regex Practice Quiz 1 - exercises to try offline.
Regex golf - Advanced exercises. Match as many phrases with as few
key strokes as possible.
Reference
Python Regex HOWTO
docs.python.org/3/library/re.html
Quick Reference - a reference sheet for looking up metacharacters.
Uses the Python syntax.
Online Regex Testers
Regex 101 - Shows matched text with explanation.
Pythex - RegEx tester using the Python re module.
regexpal - Uses JavaScript to highlight matches.
time
What it is good for?
Simple handling of times and dates.
The functions in time return the time and date in a structured format that
can be formated to custom strings.
Example
The time module offers functions for getting the current time and date.
import time
print(time.asctime())
date.strftime("%d.%m.%Y")
number = date.toordinal()
and back
datetime.date.fromordinal(7)
SQLite databases are stored in files. For using the sqlite3 module you
don't need to install or set up anything. SQLite is sufficient only for small
SQL databases, but Python modules for bigger databases look very similar.
Example
Create a new database:
import sqlite3
DB_SETUP = '''
id INTEGER,
name VARCHAR(32),
description TEXT
);'''
db = sqlite3.connect('hamlet.db')
db.executescript(DB_SETUP)
Insert data:
db.commit()
Submit a query:
result = db.execute(query)
print(list(result))
db.close()
Where to learn more?
docs.python.org/3.5/library/sqlite3.html
sys
What it is good for?
Settings of the Python interpreter itself.
The sys module provides an access point to the Python environment. You
find there command line arguments, the import path settings, the standard
input, output and error stream and many more.
Example
Command line parameters used when calling Python:
import sys
print(sys.argv)
print(sys.version)
Directories in which Python looks for modules:
print(sys.path)
sys.exit()
Most functions in this module return iterators, so you can use their result
once or convert it to a list.
Example
Concatenate a list:
import itertools
ch = itertools.chain([1,2],[3,4])
print(list(ch))
[1, 2, 3, 4]
print(list(itertools.repeat([1,2], 3)))
p = itertools.permutations([1,2,3])
print(list(p))
[(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2,
1)]
c = itertools.combinations([1,2,3], 2)
print(list(c))
Grafik
Challenge Kurzbeschreibung Rating
When your program draws a spiral with at least 3 loops, you have mastered
this challenge.
Hints
It is sufficient to draw the spiral as a series of short lines
Where is it easier to start (inside or outside)?
Both the Python modules Pillow and turtle are up to the task
Getting started
If you have no idea where to start, try the following Python script:
forward(50)
left(90)
forward(50)
Optional goals
the line width grows thicker from the inside to the outside
there is a color gradient along the spiral
Create a Postcard
Write a program that creates a postcard for the city of your choice.
1. Install Pillow
Exercise 2.2
Change the numbers in the program, so that you create a square-shaped
image.
3. Drawing shapes
Exercise 3.1
Run the program example02.py . What does it do?
Exercise 3.2
Add a broad horizontal bar to an image of your favourite city.
Exercise 3.3
for fast students
Hint: You can compose such a star from squares, triangles or polygons.
4. Drawing text
Exercise 4.1
Run the program example03.py . What does it do?
Exercise 4.2
Write the text "Welcome to (your city)" to the shape from exercise 3.2.
5. Composing images
Exercise 5.1
Run the program example04.py . What does it do?
Exercise 5.2
Create a postcard composed of four smaller pictures, the horizontal bar and
some text on it.
6. Applying filters
Exercise 6.1
Run the program example05.py . What does it do?
Exercise 6.2
Be creative!
License
(c) 2015 Dr. Kristian Rother and Magdalena Rother
Problem description
“I have a big collection of photographs, and would like to search them. I
have written a up keywords for each photograph in text files, e.g. 'flower',
'beach', 'mountain'* etc. Now I need a program that can find all photographs
for a given keyword.
The program should create a big picture that shows thumbnail images 100
pixels wide, like in the image below.”*
1. Planning
Dissect the problem into at least three separate sub-problems. Write them
down on paper (cards or a single sheet). Try to be as precise as possible.
Answer resulting questions.
When you increase n , each line gets replaced by a smaller version of the
basic shape. For, instance with n=2 you get:
And with n=5 :
When your program is able to produce a picture for 0 < n < 6 , you have
mastered this challenge.
Material:
Your favourite image(s)
Python + Pillow
MEncoder or another program to create movies from a set of images.
see the Flower Assembly Movie to get an idea how the result could
look like.
Task
Write a program using the PIL library that creates a set of .png images.
Generate the images and generate a movie from that using a non-Python
tool (e.g. MEncoder). Remember that a movie typically has 25 frames per
second.
Hints
start with a very simple movie to make sure the assembly is working
the Flower Assembly Movie was created by slowly disassembling the
picture and playing the frames backwards
Creating a movie from frames on
Windows
MEncoder requires files with the frames to have names like
frame_000123.png so that they have the right order in the final movie.
Optionale Ziele:
Das Programm gibt zufällig einen Namen aus einer vorgegebenen
Liste aus
Das Programm gibt zufällig einen Namen aus dem US-Melderegister
aus
Der Benutzer kann wahlweise Jungen- oder Mädchennamen
auswählen
Das Programm macht 10 Vorschläge
Verwende als Liste möglicher Vornamen eine Datei aus dem US-
Datensatz
Reguläre Ausdrücke
Aufgabe 1
Finde Wörter mit F im Text. Führe dazu folgendes Beispiel aus:
import re
text = "Es war einmal ein Ferkel, das hatte eine Flöte"
print(found)
Aufgabe 2
Was haben diese vier Bilder gemeinsam?
Bildquellen (links oben nach rechts unten):
print("stimmt!")
Aufgabe 3
Besuche die Seite www.regexone.com und führe einige der Übungen aus.
Aufgabe 4
Schreibe ein Programm, das E-Mail-Adressen in Text erkennt.
Aufgabe 1
Lade die Webseite www.google.de mit Python herunter.
Aufgabe 2
Extrahiere den Titel der Seite aus dem HTML-Dokument und gib ihn auf
dem Bildschirm aus.
Aufgabe 3
Führe eine Google-Suche aus Python durch. Recherchiere in der
Dokumentation zum Modul requests danach, wie Du ein Formular über
ein POST-request ausfüllen kannst.
Aufgabe 1
Suche Dir eine der folgenden Seiten aus:
Biologische Datenbanken
http://ncbi.nlm.nih.gov
Presse
http://www.reuters.com/tools/rss
Demographie
http://www.gapminder.org
Bücher
http://www.gutenberg.org
Aufgabe 2
Zeige den Quelltext der Seite/des Feeds an. Versuche, markante Elemente
zu finden, anhand derer Du den Titel, Links oder Inhalte erkennst.
Aufgabe 3
Extrahiere den Titel der Seite aus dem HTML-Dokument/Feed und gib ihn
auf dem Bildschirm aus. Verwende dazu die normalen Stringfunktionen.
Aufgabe 4
Extrahiere Links oder andere Daten aus der Seite. Entwickle dazu eine
Strategie, die entweder die Methoden von Strings, reguläre Ausdrücke oder
einen fertigen Parser verwendet.
Aufgabe 5
Lade 10 der verlinkten Seiten herunter und speichere sie ab.
Nützliche Module
requests zum Herunterladen von Webseiten
BeautifulSoup zum Parsen von HTML-Seiten
scrapy für beides zusammen
Einen Webserver mit Flask bauen
In diesem Tutorial kannst Du eine eigene dynamische HTML-Seite erstellen
und auf einem Webserver zum Laufen bringen. Wir verwenden dazu das
Python-Modul flask .
flask ist vor allem für kleinere Webseiten geeignet. Eine Alternative ist
Django , zu dem es das ausgezeichnete DjangoGirls Tutorial gibt.
1. Flask installieren
Installiere das Python-Modul flask mit pip :
app.run()
Tip:
Wir werden den Server im Verlauf des Tutorials noch sehr oft starten
müssen. Stelle sicher, dass Du das Programm aus Deinem Editor oder von
der Kommandozeile leicht anhalten und neu starten kannst.
3. HTML-Code einbinden
Die Flask-Funktionen können HTML-Code zurückgeben. Dies geht z.B. als
String mit dreifachen Anführungszeichen. Folgender HTML-Code erzeugt
eine Überschrift:
<h1>Unser Strassenverzeichnis</h1>
Baue die Überschrift in die Rückgabe der Python-Funktion ein. Starte den
Server neu. Lade die Webseite im Browser neu. Prüfe, ob Deine Überschrift
auf der Seite erscheint.
4. Eine Unterseite hinzufügen
Schreibe eine zweite Python-Funktion, die den Namen Deiner Strasse
ausgibt. Verwende den Dekorator @app.route , um die Seite auf die URL
/zuhause zu legen.
Starte den Server neu und rufe beide Unterseiten im Browser auf ( / und
/zuhause ).
Hilfe:
In der Dokumentation unter Routing
5. Hyperlinks
Erstelle auf der Startseite einen Hyperlink, der auf die Unterseite verweist.
<html>
<head><title>Unser Strassenverzeichnis</title></head>
<body>
<h1>Unser Strassenverzeichnis</h1>
</body>
</html>
Starte dann den Server neu und stelle sicher, dass der Inhalt des Templates
angezeigt wird (achte auf die Titelzeile des Browserfensters!).
7. Variablen ins Template einbinden
Wir können aus den Python-Funktionen Daten an ein Template schicken,
indem wir ein Dictionary zurückgeben:
{{ !text }}
8. Dynamische URLs
Du kannst in den URLs Platzhalter verwenden, deren Inhalt als Variable
verfügbar ist. Schreibe eine Funktion, die einen Strassennamen in der URL
erhält:
@app.route('/strasse/<strassenname>')
def strasse_anzeigen(strassenname):
...
Schreibe diese Funktion fertig und probiere die fertige Seite mit
unterschiedlichen Strassennamen aus.
Achtung:
Mit Platzhaltern kann es leicht passieren, dass zwei Funktionen die gleiche
URL ansprechen. Dies kann zu interessanten Fehlern führen, weil nicht
sofort ersichtlich ist, welche Funktion Flask aufruft.
9. Geodaten bereitstellen
Als Datensatz verwenden wir das Strassennamenverzeichnis der Zeit. Die
Daten liegen ursprünglich im Format GeoJSON vor. Wir verwenden eine
Datei, die in das .csv -Format umgewandelt wurde, so dass Du es bequem
mit pandas verwenden kannst.
Wähle einige Strassen aus der Datei aus und stelle diese auf der Webseite
als Tabelle dar. Lies dazu nach, wie Du eine for -Schleife im Template
unterbringst.
10. Ein Formular erstellen
Recherchiere, wie Du ein Formular mit Flask erstellst. Baue ein Formular
ein, in dem Du einen Strassennamen in ein Eingabefeld eingibst und über
einen Knopf das Formular abschickst.
11. Kopf- und Fußzeilen
Du kannst Deine Templates auf mehrere Dateien aufteilen, um
Redundanzen zu vermeiden. Erstelle eine Datei für Kopf- und Fusszeilen.
Anmerkung:
Oft ist es nicht wünschenswert, Dateien von einer Drittpartei einzubinden.
Nachhaltiger ist es, diese als statische Dateien auf Deinem eigenen Server
abzulegen.
15. Eine SQL-Datenbank verwenden
Es ist natürlich nicht grade effizient, bei jedem Neustart des Servers 900
MB Daten in den Speicher zu laden. Eine bessere Alternative ist eine
Datenbank. Verwende das Python-Modul sqlite3 , um eine Datenbank
zu erstellen und die gewünschten Strassen aus einer Tabelle abzufragen.
16. Deployment auf einem öffentlichen
Server
Lies Dir im Djangogirls-Tutorial durch, wie Du einen Server auf
pythonanywhere anlegst. Probiere es aus! Es kostet nichts.
Hinweis:
Es ist sehr zu empfehlen, den Code mit git zu veröffentlichen, bevor Du
Dich mit dem öffentlichen Server beschäftigst. Dadurch werden viele
Einzelheiten deutlich einfacher.
Blog
Das Projekt besteht darin, eine eigene Webseite zu entwickeln und im Netz
zu veröffentlichen. Das Django Girls Tutorial bietet eine ausgezeichnete
Anleitung.
Ziel:
Die Webseite ist über einen Browser erreichbar.
Themen:
Server-Programmierung, HTML, Deployment
Python-Bibliotheken:
Django oder Bottle