Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
15 views

Dokumen - Pub Python 3 Module Examples

Uploaded by

Rahul Rajput
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

Dokumen - Pub Python 3 Module Examples

Uploaded by

Rahul Rajput
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 109

Table of Contents

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)

Distributed under the conditions of the Creative Commons Attribution


Share-alike License 4.0

Sources of this document can be found on


https://github.com/krother/Python3_Module_Examples
Purpose of this e-book
This e-book contains my favourite Python modules. Every module comes
with a brief description and a code example.

This document is for you if:

you know a little bit of Python already


you would like to know what Python modules are there
you find the amount of Python modules overwhelming
you find the full documentation too heavy to begin
you would like to try a few simple examples

Have fun getting to know Python better!


Overview
csv
What it is good for?
Read and write comma-separated-value (CSV) files.

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.

Installed with Python by default


yes

Example
Write a table with two rows to a CSV file:
import csv

data = [["first", 1, 234],

["second", 5, 678]]

outfile = open('example.csv', 'w')

writer = csv.writer(outfile, delimiter=';', quotechar='"')

writer.writerows(data)

outfile.close()

Read the file again:

for row in csv.reader(open('example.csv'), delimiter=';'):

print(row)

['first', '1', '234']

['second', '5', '678']

Where to learn more?


https://docs.python.org/3/library/csv.html
json
What it is good for?
Convert Python dictionaries to JSON and back.

The JavaScript Object Notation (JSON) is frequently used to send


structured data around the web or store it painlessly in files. The json

modules utilizes the similarity of the JSON format to Python dictionaries.

Installed with Python by default


yes

Example
Convert a dictionary to a JSON-formatted string:

import json

data = {'first': 1, 'second': 'two', 'third': [3,4,5]}

jj = json.dumps(data)

print(jj)

'{"second": "two", "first": 1, "third": [3, 4, 5]}'


Convert JSON string back to a Python dictionary:

d = json.loads(jj)

print(d)

{'second': 'two', 'first': 1, 'third': [3, 4, 5]}

Where to learn more?


https://docs.python.org/3/library/json.html
xml
What it is good for?
Parse XML files.

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.

Installed with Python by default


yes

Example
Sample XML data:

<?xml version="1.0" encoding="UTF-8" ?>

<actor_list>

<actor name="Hamlet">the Prince of Denmark</actor>

<actor name="Polonius">Ophelias father</actor>

</actor_list>

Read an XML file and extract content from tags:


from xml.dom.minidom import parse

document = parse('hamlet.xml')

actors = document.getElementsByTagName("actor")

for act in actors:

name = act.getAttribute('name')

for node in act.childNodes:

if node.nodeType == node.TEXT_NODE:

print("{} - {}".format(name, node.data))

Hamlet - the Prince of Denmark

Polonius - Ophelias father

Where to learn more?


https://docs.python.org/3/library/xml.html
zipfile
What it is good for?
Read and write .zip files.

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.

Installed with Python by default


yes

Example
Create a new zip archive and add files to it:

import zipfile

z = zipfile.ZipFile('archive.zip', 'w')

z.write('myfile.txt') # has to exist

z.writestr('test.txt', 'Hello World') # new

z.close()

List contents of the newly created zip file:


z = zipfile.ZipFile('archive.zip')

print(z.namelist())

Extract a file to a new folder:

print(z.extract('test.txt', 'myfolder'))

z.close()

Where to learn more?


docs.python.org/3/library/zipfile.html
numpy
What it is good for?
numpy makes it easy to work with matrices in Python.

Because it is implemented in C, numpy accelerates many calculations. It is


also type-safe - all elements of a matrix have the same type. Many of the
most powerful Python libraries like pandas , scikit-learn and PILLOW

have been built on top of numpy.

Pre-installed on Anaconda?
yes

How to install it?

pip install numpy

Example
Creating a 4 x 2 matrix and adding 10 to each element
import numpy as np

vector = np.array([[0, 1, 2, 3], [4, 5, 6, 7]])

print(vector + 10)

[[10 11 12 13]

[14 15 16 17]]

print(vector.shape)

(2, 4)

Where to learn more?


http://www.numpy.org/
pandas
What it is good for?
Analyze tabular data.

pandas is an extremely powerful library to analyze, combine and


manipulate data in many thinkable (and some unthinkable) ways. The tables
called DataFrame have many similarities to R. DataFrames have an index
column and functions for plotting and reading from CSV or Excel files are
included by default. Pandas uses numpy under the hood.

Installed with Python by default


no

Installed with Anaconda


yes

How to install it?

pip install pandas


Example
Create a table with characters and numbers.:

import pandas as pd

hamlet = [['Hamlet', 1.76], ['Polonius', 1.52], ['Ophelia',

1.83], ['Claudius', 1.95]]

df = pd.DataFrame(data = hamlet, columns = ['name', 'size'])

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)

tall = sorted[sorted['size'] > 1.70]

print(tall.head(2))

name size

3 Claudius 1.95

2 Ophelia 1.83

df.to_csv('hamlet.csv', index=False, header=True)

Where to learn more?


http://pandas.pydata.org/
scipy
What it is good for?
Scientific calculations.

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 .

Installed with Python by default


no

Installed with Anaconda


yes

How to install it?

pip install scipy


Example
Define a square function; create noisy X/Y data using numpy :

def func(x, a, b):

return a * x**2 + b

import numpy as np

x = np.linspace(-10, 10, 100)

y = func(x, 1, 5)

ynoise = y + 20 * np.random.laplace(size=len(x))

Fit the parameters of the function with noisy data:

from scipy.optimize import curve_fit

params, pcov = curve_fit(func, x , ynoise)

yfit = func(x, params[0], params[1])

Plot the outcome:

import matplotlib.pyplot as plt

fig = plt.figure

plt.plot(x, yfit, "k-")

plt.plot(x, ynoise, "bx")

plt.savefig('fit.png')
Where to learn more?
http://scipy.org/
scikit-learn
What it is good for?
Machine Learning.

The scikit-learn library contains regression and classification methods


ranging from simple linear regression over logistic regression, Support
Vector Machines and multiple clustering methods to sophisticated things
like Random Forests. In addition, rich functions for validating predictions
exist.

Installed with Python by default


no

Installed with Anaconda


yes

How to install it?

pip install scikit-learn


Example
Load one of the example datasets and divide it into a training and test set:

from sklearn import svm, datasets, cross_validation

iris = datasets.load_iris()

X_train, X_test, Y_train, Y_test = \

cross_validation.train_test_split(iris.data, iris.target, \

test_size=0.4, random_state=True)

Fit a Support Vector Machine model and test it:

svc = svm.SVC(kernel='linear', C=1.0,

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'))

[ 0.96666667 1. 0.96666667 0.96666667 1. ]


Where to learn more?
http://scipy.org/
matplotlib
What it is good for?
Plotting diagrams.

matplotlib is capable of producing static images of all common types of


diagrams in print quality: line plots, scatter plots, bar charts, pie charts,
histograms, heat maps etc.

Installed with Anaconda


yes

How to install it:

pip install matplotlib

Example
Plot a square function:
from pylab import *

x = list(range(-10, 10))

y = [xval**2 for xval in x]

figure()

plot(x, y, 'bo') # blue circles

title('square function')

xlabel('x')

ylabel('$x^2$')

savefig('plot.png')

output from matplotlib

Where to learn more?


http://matplotlib.org/
PILLOW
What it is good for?
Image manipulation.

PILLOW is the inofficial successor to the Python Imaging Library


( PIL ). It facilitates creating, cutting and applying various filters to pixel-
based images.

Installed with Python by default


no

Installed with Anaconda


yes

How to install it?

pip install pillow

Example
Convert all .png images in the directory to half their size.
from PIL import Image

import os

for filename in os.listdir('.'):

if filename.endswith('.png'):

im = Image.open(filename)

x = im.size[0] // 2

y = im.size[1] // 2

small = im.resize((x, y))

small.save('sm_' + filename)

Where to learn more?


https://pillow.readthedocs.org
requests
What it is good for?
Retrieving webpages.

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.

Installed with Python by default


no

Installed with Anaconda


yes

Example
Read the homepage of the author.
import requests

r = requests.get('http://www.academis.eu')

print(r.text)

Search scientific articles on PubMed:

url =

"http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi"

param_dict = {'db':'pubmed', 'term':'escherichia',

'rettype':'uilist'}

r = requests.get(url, params=param_dict)

print(r.text)

Where to learn more?


http://docs.python-requests.org/en/latest/index.html
BeautifulSoup
What it is good for?
Parsing HTML pages.

Beautiful soup is much, much easier to use than the default HTML parser
installed with Python.

Installed with Python by default


no

Installed with Anaconda


no

How to install it?

pip install bs4

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"""

soup = BeautifulSoup(html, "lxml")

for ul in soup.find_all('ul'):

if "cast" in ul.get('class', []):

for item in ul.find_all('li'):

print(item.get_text(), end=", ")

Where to learn more?


http://www.crummy.com/software/BeautifulSoup/bs4/doc/
paramiko
What it is good for?
Executing commands via SSH.

paramiko allows you to execute Unix commands on another machine by


logging in via SSH. The fabric module gives you a comfortable interface
built on top of paramiko .

Installed with Python by default


no

Installed with Anaconda


yes

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")

stdin, stdout, stderr = client.exec_command('ls -l')

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

Where to learn more?


www.paramiko.org/
math
What it is good for?
math contains mathematical functions similar to a scientific calculator.

In the module, you find various trigonometric and exponential functions. In


addition the two constants pi and e are included.

Installed with Python by default


yes

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))

Where to learn more?


https://docs.python.org/3/library/math.html
os
What it is good for?
Working with files and directories.

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.

Installed with Python by default


yes

Example
Change directory and list its contents:
import os

os.chdir('/home/krother/python_modules/')

os.listdir('.')

['sys.md', 'os.md', 'csv.md', 're.md', 'random.md',

'pprint.md', 'numpy.md', 'time.md', 'itertools.md',

'json.md', 'template.md', 'math.md', 'urllib.md']

Check whether a file exists:

os.path.exists('os.md')

Copy a file and remove it afterwards:

os.system('cp os.md copy.md')

os.remove('copy.md')

Where to learn more?


https://docs.python.org/3/library/os.html
random
What it is good for?
Generate random numbers.

random contains generators for the most common distributions.

Installed with Python by default


yes
Example
Creating random integers
One most wanted function is to create random integers in a given range:

dice = random.randint(1,6)

Creating random floats


The random() functin generates float numbers between 0 and 1:

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)

Creating random lists


Random combinations of elements with repetition:
from random import choice

bases = ['A','C','G','T']

dna = [choice(bases) for i in range(20)]

print ''.join(dna)

When elements are to be picked without repetition, you would use, the
sample function:

from random import sample

flavors = ['vanilla','banana','mint']

icecream = sample(flavors, 2)

Where to learn more?


https://docs.python.org/3/library/random.html
re
What it is good for?
Pattern matching in text.

The re module implements Regular Expression, a powerful syntax for


searching patterns in text. Regular Expressions are available in most
programming languages. You need to learn some special characters to build
your own patterns.

Installed with Python by default


yes

Example

import re

text = "the quick brown fox jumps over the lazy dog"

Search for o and show adjacent characters:


re.findall(".o.", text)

print(re.findall(".o.", text))

['row', 'fox', ' ov', 'dog']

Search for three-letter words enclosed by whitespace:

print(re.findall("\s(\wo\w)\s*", text))

['fox', 'dog']

Substitute any of dflj by a w :

print(re.sub("[dflj]", "w", text))

'the quick brown wox wumps over the wazy wog'

Check if jumps or swims occurs and return details:

print(re.search('jumps|swims', text))

<_sre.SRE_Match object; span=(20, 25), match='jumps'>


Where to learn more?

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.

Installed with Python by default


yes

Example
The time module offers functions for getting the current time and date.

import time

print(time.asctime())

print(time.strftime('%a %d.%m.', time.localtime()))

Wait for two seconds:


time.sleep(2)

The datetime module also helps to format dates:

date = datetime.date(2015, 12, 24)

date.strftime("%d.%m.%Y")

Dates can be converted to integer numbers:

date = datetime.date(2015, 12, 24)

number = date.toordinal()

and back

datetime.date.fromordinal(7)

Where to learn more?


https://docs.python.org/3/library/time.html
https://docs.python.org/3/library/time.html
sqlite3
What it is good for?
Create and use a SQLite database.

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.

Installed with Python by default?


yes

Example
Create a new database:
import sqlite3

DB_SETUP = '''

CREATE TABLE IF NOT EXISTS person (

id INTEGER,

name VARCHAR(32),

description TEXT

);'''

db = sqlite3.connect('hamlet.db')

db.executescript(DB_SETUP)

Insert data:

query = 'INSERT INTO person VALUES (?,?,?)'

db.execute(query, (1, "Hamlet", "the prince of Denkmark"))

db.execute(query, (2, "Polonius", "Ophelias father"))

db.commit()

Submit a query:

query = '''SELECT name, description FROM person'''

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.

Installed with Python by default


yes

Example
Command line parameters used when calling Python:

import sys

print(sys.argv)

Version of the Python interpreter:

print(sys.version)
Directories in which Python looks for modules:

print(sys.path)

Exit Python altogether:

sys.exit()

Where to learn more?


https://docs.python.org/3/library/sys.html
itertools
What it is good for?
Functions to work with lists and iterators.

Most functions in this module return iterators, so you can use their result
once or convert it to a list.

Installed with Python by default


yes

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)))

[[1, 2], [1, 2], [1, 2]]

Permutations and combinations of list elements:

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))

[(1, 2), (1, 3), (2, 3)]


Where to learn more?
https://docs.python.org/3/library/itertools.html
Challenges

Grafik
Challenge Kurzbeschreibung Rating

Spirale Zeichne eine Spirale sehr leicht

Postcards Zeichne eine Postkarte leicht

Thumbnails Erzeuge Thumbnails von Bildern mittel

Rekursive Grafik Zeichne rekursive Bilder mittel

Film Drehe einen kurzen Film schwer


Daten
Challenge Kurzbeschreibung Rating

Babynamengenerator Erzeuge zufällige Babynamen leicht

Reguläre Ausdrücke Suche Muster in Text mittel

Google Führe eine Google-Suche durch mittel

Webrecherche Lade Webseiten herunter mittel


Webentwicklung
Challenge Kurzbeschreibung Rating

Daten anzeigen Erstelle einen einfachen Bottle-Webserver mittel

Blog Erstelle eine Blog-Webseite mit Django schwer


Coding Challenge: Spiral
The Challenge
Write a program, that draws a spiral:

When your program draws a spiral with at least 3 loops, you have mastered
this challenge.

What you can practise in this coding challenge


loops
The Pillow library in Python
The turtle module in Python

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:

from turtle import forward, left

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

`pip install pillow`

(it is already installed with Anaconda)


2. Learn to know PIL
Exercise 2.1
Run the program example01.py . What does it do?

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

Draw a 8-pointed star on an image of your favourite city.

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

Distributed under the conditions of the Creative Commons Attribution


Share-alike License 4.0
Thumbnail Generator

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.”*

Rick Closeview , hobby photographer


Instructions
Implement a program according to the problem description. The following
steps may be helpful:

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.

2. Divide the program into functions


Identify key functions your program needs to have. Decide what should be
the input and output for each of them. Write them up as well.

3. Get the Graphics


The file sample_photos.zip contains a few example photographs. It also
contains a file pics.txt in each subfolder. This is the input information
for the program.

4. Explore Python libraries


You might want to take a closer look at:
os for file handling
Pillow for image manipulation

5. Write the program


After these steps, start implementing.
Coding Challenge: The Recursive
Snowflake
The Challenge
Write a program, that for a parameter n=1 creates a basic shape out of four
straight lines:

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.

What you can exercise in this coding challenge:


Recursive algorithms
The Pillow library in Python
The turtle module in Python
Create a Movie

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.

1. Collect all frame images in one directory


2. copy Mencoder into that directory.
3. open a console ( Start -> Execute -> cmd )
4. switch with cd <directory_name> to that directory
5. type

mencoder "mf://*.png" -mf fps=25 -o output.avi -ovc lavc -lavcopts


vcodec=mpeg4
Babynamengenerator
Programmiere einen Babynamengenerator für unentschlossene Eltern.

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"

found = re.findall('(F\w+)[^\w]', text, re.IGNORECASE)

print(found)

Aufgabe 2
Was haben diese vier Bilder gemeinsam?
Bildquellen (links oben nach rechts unten):

By Source (WP:NFCC#4), Fair use


Die Autorenschaft wurde nicht in einer maschinell lesbaren Form
angegeben. Es wird Swarve~commonswiki als Autor angenommen, CC
BY-SA 3.0
Gaël Marziou from Grenoble, France - IMG_6266_DXO, CC BY 2.0
Derfu, CC BY-SA 3.0

Führe folgendes Codebeispiel aus:


import re

text = input("Was ist auf einem der Bilder zu sehen? ")

if re.search(r"^(\w+)i(\w+)[- ]\1o\2", text):

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.

Verwende die Funktion re.findall und erstelle ein entsprechendes


Suchmuster.

Auf Regex101 kannst Du den regulären Ausdruck testen.


Google
Überprüfe mit einem Python-Programm, ob die Suchmaschine Google
funktioniert.

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.

Gib die Suchergebnisse auf dem Bildschirm aus.


Hinweise:
Das Modul requests hilft beim Vorbereiten der Suchanfrage.
Das Formular verwendet HTTP POST.
Es gibt im Formular mindestens ein 'hidden'-Feld, das Du angeben
mußt.
Herunterladen von HTML-Seiten
In den folgenden Aufgaben laden wir Daten von einer statischen Webseite
oder einem RSS-Feed herunter.

Aufgabe 1
Suche Dir eine der folgenden Seiten aus:

RSS-Feeds des Parlaments


https://www.parlament-berlin.de/de/Service/RSS-Feeds

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 :

pip install flask


2. Eine minimale Webseite starten
Erstelle ein Python-Programm server.py , und baue das Hello-World-
Beispiel aus der Flask-Dokumentation nach.

Füge folgende Zeile zum Programm hinzu (funktioniert mit Anaconda


besser als die in der Dokumentation angegebene Methode):

app.run()

Starte das Programm. Finde heraus, unter welcher HTTP-Adresse der


Server läuft. Setze diese Adresse im Browser ein und prüfe, ob Dein Server
erreichbar ist.

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>

Mehr zu HTML-Elementen erfährst Du auf Selfhtml.org.

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.

Dazu muss die Funktion hello() folgenden HTML-Code zurückgeben:

<a href="/zuhause">Meine Strasse anzeigen</a>

Starte den Server neu und prüfe, ob der Link funktioniert.


6. Ein Template hinzufügen
Es wird schnell beschwerlich, eine ganze HTML-Seite in unser Python-
Skript zu kleben. Es ist besser, den HTML-Code in Templates zu speichern
und diese einzubinden.

Erstelle eine Datei templates/hello.html , in die Du den folgenden


HTML-Code einfügst:

<html>

<head><title>Unser Strassenverzeichnis</title></head>

<body>

<h1>Unser Strassenverzeichnis</h1>

<a href="/zuhause">Meine Strasse anzeigen</a>

</body>

</html>

Binde das Template entsprechend dem Abschnitt Rendering Templates aus


der Flask-Dokumentation hinzu.

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:

return {'text': "Hallo" }

In den HTML-Templates kannst Du diese Variablen folgendermassen


ansprechen:

{{ !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.

Wie das in Flask geht findest Du unter Template Inheritance.


12. CSS-Stylesheets einbinden
Hier kannst Du Typographie und Farben festlegen.

Lies unter Selfhtml.org nach, wie CSS-Befehle aussehen.


Baue einen CSS-Befehl in eines der Templates ein, der die Überschrift
einfärbt.
Erstelle eine Datei static/style.css , in die Du eine weitere CSS-
Anweisung schreibst.
Binde die CSS-Datei in Dein Template ein (schreibt Dozent an).
Sage Flask, wo die CSS-Datei zu finden ist. Siehe Static Files
13. Eine Karte mit Folium zeichnen
Stelle die gefundenen Strassen als interaktive Karte dar. Probiere dazu
zunächst ein Python-Skript mit dem Modul folium aus. Siehe
https://github.com/krother/python_showcase/tree/master/map_markers.
14. Bootstrap
"Half the internet is built on Bootstrap"

Bootstrap ist eine Sammlung nützlicher CSS- und JavaScript-Elemente,


mit denen Du schnell eine Typographie hinbekommst, die auch auf
Mobilgeräten gut aussieht.

Dazu ist eine Reihe von Schritten nötig:

Binde die Bootstrap-Dateien in Deine Templates ein (siehe Anleitung)


Probiere eine Vorlage aus der Dokumentation aus
Probiere einzelne Elemente aus (unter "Components" findest Du
einige, bei denen Du leicht siehst, ob sie funktionieren)

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

You might also like