english translation started

This commit is contained in:
2026-02-22 18:22:46 +01:00
parent 19c67a3c9b
commit 9e418381ca
17 changed files with 1915 additions and 1907 deletions

View File

@@ -2,7 +2,23 @@
engine: julia
---
# Ein- und Ausgabe
```{julia}
#| error: false
#| echo: false
#| output: false
using InteractiveUtils
import QuartoNotebookWorker
Base.stdout = QuartoNotebookWorker.with_context(stdout)
```
```{julia}
#| error: false
#| echo: false
#| output: false
flush(stdout)
```
# Input and Output
```{julia}
@@ -22,51 +38,50 @@ Base.active_module() = myactive_module()
```
## Konsole
## Console
Das Betriebssystem stellt für ein Programm üblicherweise 3 Kanäle _(streams)_ zur Verfügung:
The operating system normally provides 3 channels (_streams_) for a program:
- Standardeingabekanal `stdin`
- Standardausgabekanal `stdout` und
- Standardfehlerausgabekanal `stderr`.
- Standard input channel `stdin`
- Standard output channel `stdout` and
- Standard error output channel `stderr`.
Wenn das Programm in einem Terminal (oder Konsole bzw. Shell) gestartet wird, kann das Programm über `stdin` die Tastatureingaben
einlesen und Ausgaben über `stdout` sowie `stdout` erscheinen im Terminal.
When the program is started in a terminal (or console or shell), the program can read keyboard input via `stdin` and output appears in the terminal via `stdout` and `stdout`.
- Schreiben nach `stdout`: `print()`,`println()`,`printstyled()`
- Schreiben nach `stderr`: `print(strerr,...)`, `println(stderr,...)`, `printstyled(stderr,...)`
- Lesen von `stdin`: `readline()`
- Writing to `stdout`: `print()`,`println()`,`printstyled()`
- Writing to `stderr`: `print(strerr,...)`, `println(stderr,...)`, `printstyled(stderr,...)`
- Reading from `stdin`: `readline()`
### Eingaben
### Input
Die Sprache _Python_ stellt eine Funktion `input()` zur Verfügung:
The language _Python_ provides a function `input()`:
```{.python}
ans = input("Bitte eine positive Zahl eingeben!")
ans = input("Please enter a positive number!")
```
Die Funktion gibt den Prompt aus, wartet auf eine Eingabe und liefert die
Eingabe als `string` zurück.
The function prints the prompt, waits for input, and returns the
input as a `string`.
In Julia kann man diese Funktion so implementieren:
In Julia, you can implement this function as follows:
```{julia}
function input(prompt = "Eingabe:")
function input(prompt = "Input:")
println(prompt)
flush(stdout)
return chomp(readline())
end
```
**Anmerkungen**
**Comments**
- Schreibanweisungen werden von modernen Betriebssystemen gebuffert. Mit `flush(stdout)` wird die Leerung des Buffers und sofortige Schreiboperation erzwungen.
- `readline()` liefert einen String zurück, der mit einer Newline `\n` endet. Die Funktion `chomp()` entfernt einen eventuellen Zeilenumbruch vom Ende eines Strings.
- Write instructions are buffered by modern operating systems. With `flush(stdout)`, the buffer is emptied and the write operation is forced to complete immediately.
- `readline()` returns a string ending with a newline `\n`. The function `chomp()` removes a possible line break from the end of a string.
```{julia}
#| eval: false
a = input("Bitte 2 Zahlen eingeben!")
a = input("Please enter 2 numbers!")
```
```{julia}
#| echo: false
@@ -74,32 +89,33 @@ a = "34 56"
```
### Verarbeitung der Eingabe
### Processing the Input
> `split(str)` zerlegt einen String in "Wörter" und liefert einen _(array of strings)_:
> `split(str)` splits a string into "words" and returns an _(array of strings)_:
```{julia}
av = split(a)
```
> `parse(T, str)` versucht, `str` in den Typ `T` umzuwandeln:
> `parse(T, str)` tries to convert `str` to type `T`:
```{julia}
v = parse.(Int, av)
```
`parse()` erzeugt einen Fehler, wenn der String sich nicht als Wertangabe von Typ `T` parsen lässt. Man kann den Fehler mit
`try/catch` abfangen oder die Funktion `tryparse(T, str)` verwenden, die in so einem Fall `nothing` zurückgibt - worauf man dann
z.B. mit `isnothing()` testen kann.
`parse()` generates an error if the string cannot be parsed as a value of type `T`. You can catch the error with
`try/catch` or use the function `tryparse(T, str)`, which returns `nothing` in such a case - on which you can then
e.g. test with `isnothing()`.
### Einzelne Tastenanschläge einlesen
- `readline()` u.ä. warten auf den Abschluss der Eingabe durch Drücken der `Enter`-Taste.
- Techniken zum Einlesen einzelner _keystrokes_ findet man hier:
### Reading Individual Keystrokes
- `readline()` and similar functions wait for the input to be completed by pressing the `Enter` key.
- Techniques for reading individual _keystrokes_ can be found here:
- [https://stackoverflow.com/questions/56888266/how-to-read-keyboard-inputs-at-every-keystroke-in-julia](https://stackoverflow.com/questions/56888266/how-to-read-keyboard-inputs-at-every-keystroke-in-julia)
- [https://stackoverflow.com/questions/60954235/how-can-i-test-whether-stdin-has-input-available-in-julia](https://stackoverflow.com/questions/60954235/how-can-i-test-whether-stdin-has-input-available-in-julia)
@@ -107,30 +123,30 @@ z.B. mit `isnothing()` testen kann.
## Formatierte Ausgabe mit dem `Printf`-Makro
## Formatted Output with the `Printf` Macro
Oft möchte man Zahlen oder Strings mit einer strikten Formatvorgabe - Gesamtlänge, Nachkommastellen, rechts/linksbündig usw - ausgeben.
Often you want to output numbers or strings with a strict format specification - total length, decimal places, right/left-aligned, etc.
Dazu definiert das Paket `Printf` die Makros `@sprintf` und `@printf`, welche sehr ähnlich wie die gleichnamigen C-Funktionen arbeiten.
To this end, the `Printf` package defines the macros `@sprintf` and `@printf`, which work very similarly to the corresponding C functions.
```{julia}
using Printf
x = 123.7876355638734
@printf("Ausgabe rechtsbündig mit max. 10 Zeichen Platz und 3 Nachkommastellen: x= %10.3f", x)
@printf("Output right-aligned with max. 10 character width and 3 decimal places: x= %10.3f", x)
```
Das erste Argument ist ein String, der Platzhalter (hier: `%10.3`) für auszugebende Variablen enthält; gefolgt von diesen Variablen als weitere Argumente.
The first argument is a string containing placeholders (here: `%10.3`) for variables to be output; followed by these variables as further arguments.
Platzhalter haben die Form
Placeholders have the form
```
%[flags][width][.precision]type
```
wobei die Angaben in eckigen Klammern alle optional sind.
where the entries in square brackets are all optional.
**Typangaben im Platzhalter**
**Type specifications in placeholders**
| | |
|:--|:------------|
@@ -149,9 +165,9 @@ wobei die Angaben in eckigen Klammern alle optional sind.
| | |
|:----|:-----|
|Pluszeichen| rechtsbündig (Standard)|
|Minuszeichen| linksbündig|
|Null| mit führenden Nullen|
|Plus sign| right-aligned (default)|
|Minus sign| left-aligned|
|Zero| with leading zeros|
: {.striped .hover}
@@ -159,37 +175,37 @@ wobei die Angaben in eckigen Klammern alle optional sind.
**Width**
```
Anzahl der minimal verwendeten Zeichen (wenn nötig, werden auch mehr genommen)
Number of minimum characters used (more will be taken if necessary)
```
### Beispiele:
### Examples:
```{julia}
using Printf # Paket laden nicht vergessen!
using Printf # Don't forget to load the package!
```
```{julia}
@printf("|%s|", "Hallo") # string mit Platzhalter für String
@printf("|%s|", "Hello") # string with placeholder for string
```
Die senkrechten Striche sind nicht Teil des Platzhalters. Sie sollen die Begrenzung des Ausgabefeldes anzeigen.
The vertical bars are not part of the placeholder. They are intended to indicate the boundaries of the output field.
```{julia}
@printf("|%10s|", "Hallo") # Minimallänge, rechtsbündig
@printf("|%10s|", "Hello") # Minimum length, right-aligned
```
```{julia}
@printf("|%-10s|", "Hallo") # linksbündig
@printf("|%-10s|", "Hello") # left-aligned
```
```{julia}
@printf("|%3s|", "Hallo") # Längenangabe kann überschritten werden
# besser eine 'kaputt formatierte' Tabelle als falsche Werte!
@printf("|%3s|", "Hello") # Length specification can be exceeded
# Better a 'badly formatted' table than incorrect values!
```
@@ -198,37 +214,36 @@ j = 123
k = 90019001
l = 3342678
@printf("j= %012i, k= %-12i, l = %12i", j, k, l) # 0-Flag für führende Nullen
@printf("j= %012i, k= %-12i, l = %12i", j, k, l) # 0-flag for leading zeros
```
`@printf` und `@sprintf` können wie alle Makros wie Funktionen aufgerufen werden:
`@printf` and `@sprintf` can be called like functions or as macros:
```{julia}
@printf("%i %i", 22, j)
```
-- oder wie Makros, also ohne Funktionsklammern und ohne Komma:
-- or as macros, i.e., without function parentheses and without comma:
```{julia}
@printf "%i %i" 22 j
```
`@printf` kann als erstes Argument noch einen Stream übergeben bekommen.
`@printf` can take a stream as its first argument.
Ansonsten besteht die Argumentliste aus
Otherwise, the argument list consists of
- Formatstring mit Platzhaltern
- Variablen in der Reihenfolge der Platzhalter, in Anzahl und Typ zu den Platzhaltern passend
- format string with placeholders
- variables in the order of the placeholders, matching in number and type to the placeholders
```{julia}
@printf(stderr, "Erstes Resultat: %i %s\nZweites Resultat %i",
j, "(geschätzt)" ,k)
@printf(stderr, "First result: %i %s\nSecond result %i",
j, "(estimated)" ,k)
```
Das Makro `@sprintf` druckt nichts, sondern liefert den ausgefüllten formatierten String zurück:
The macro `@sprintf` does not print anything but returns the filled formatted string:
```{julia}
@@ -240,52 +255,52 @@ str = @sprintf("x = %10.6f", π );
str
```
### Formatierung der Gleitkommazahlen:
### Formatting Floating Point Numbers:
Bedeutung des _Precision_-Wertes:
Meaning of the _precision_ value:
- `%f` und `%e`-Format: maximale Anzahl der Nachkommastellen
- `%g`-Format: maximale Anzahl von ausgegebenen Ziffern (Vor- + Nachkommastellen)
- `%f` and `%e` format: maximum number of decimal places
- `%g` format: maximum number of digits output (integer + decimal places)
```{julia}
x = 123456.7890123456
@printf("%20.4f %20.4e", x, x) # 4 Nachkommastellen
@printf("%20.4f %20.4e", x, x) # 4 decimal places
```
```{julia}
@printf("%20.7f %20.7e", x, x) # 7 Nachkommastellen
@printf("%20.7f %20.7e", x, x) # 7 decimal places
```
```{julia}
@printf("%20.7g %20.4g", x, x) # insgesamt 7 bzw. 4 Stellen
@printf("%20.7g %20.4g", x, x) # total 7 and 4 digits respectively
```
## Dateioperationen
## File Operations
Dateien werden
Files are
- geöffnet $\Longrightarrow$ dabei ensteht ein neues _stream_-Objekt (zusätzlich zu `stdin, stdout, stderr`)
- dann kann dieser _stream_ gelesen und geschrieben werden
- geschlossen $\Longrightarrow$ _stream_-Objekt wird von Datei getrennt
```{.julia}
stream = open(path, mode)
```
- path: Dateiname/pfad
- mode:
- opened $\Longrightarrow$ a new _stream_-object is created (in addition to `stdin, stdout, stderr`)
- then this _stream_ can be read from and written to
- closed $\Longrightarrow$ _stream_-object is detached from file
```{.julia}
stream = open(path, mode)
```
- path: filename/path
- mode:
```
"r" read, öffnet am Dateianfang
"w" write, öffnet am Dateianfang (Datei wird neu angelegt oder überschrieben)
"a" append, öffnet zum Weiterschreiben am Dateiende
```
```
"r" read, opens at file beginning
"w" write, opens at file beginning (file is created or overwritten)
"a" append, opens to continue writing at file end
```
Schreiben wir mal eine Datei:
Let's write a file:
```{julia}
file = open("datei.txt", "w")
@@ -298,7 +313,7 @@ file = open("datei.txt", "w")
```{julia}
println(file, " zweite Zeile")
println(file, " second line")
```
@@ -306,59 +321,58 @@ println(file, " zweite Zeile")
close(file)
```
Schauen wir uns die Datei an:
Let's look at the file:
```{julia}
;cat datei.txt
```
...und jetzt öffnen wir sie wieder zum Einlesen:
...and now we open it again for reading:
```{julia}
stream = open("datei.txt", "r")
```
`readlines(stream)` liefert alle Zeilen einer Textdatei als Vector von Strings.
`readlines(stream)` returns all lines of a text file as a vector of strings.
`eachline(stream)` liefert einen Iterator über die Zeilen der Datei.
`eachline(stream)` returns an iterator over the lines of the file.
```{julia}
n = 0
for line in eachline(stream) # Lese zeilenweise
for line in eachline(stream) # Read line by line
n += 1
println(n, line) # Drucke mit Zeilennummer
println(n, line) # Print with line number
end
close(stream)
```
## Pakete für Dateiformate
## Packages for File Formats
Für die Ein- und Ausgabe in den verschiedensten Dateiformaten existieren Julia-Pakete, z.B.
For input and output in various file formats, there are Julia packages, e.g.,
- [PrettyTables.jl](https://ronisbr.github.io/PrettyTables.jl/stable/) Ausgabe von formatierten Tabellen
- [DelimitedFiles.jl](https://docs.julialang.org/en/v1/stdlib/DelimitedFiles/) Ein- und Ausgabe von Matrizen u.ä.
- [CSV.jl](https://csv.juliadata.org/stable/) Ein- und Ausgabe von Dateien mit "comma-separated values" u.ä.
- [XLSX.jl](https://felipenoris.github.io/XLSX.jl/stable/tutorial/) Ein- und Ausgabe von Excel-Dateien
- [PrettyTables.jl](https://ronisbr.github.io/PrettyTables.jl/stable/) Output of formatted tables
- [DelimitedFiles.jl](https://docs.julialang.org/en/v1/stdlib/DelimitedFiles/) Input and output of matrices, etc.
- [CSV.jl](https://csv.juliadata.org/stable/) Input and output of "comma-separated values" files, etc.
- [XLSX.jl](https://felipenoris.github.io/XLSX.jl/stable/tutorial/) Input and output of Excel files
und viele andere mehr...
and many more...
### DelimitedFiles.jl
Dieses Paket ermöglicht das bequeme Abspeichern/Einlesen von Matrizen. Dazu stellt es die Funktionen `writedlm()` und `readdlm()` zur
Verfügung.
This package enables convenient saving/reading of matrices. It provides the functions `writedlm()` and `readdlm()`.
```{julia}
using DelimitedFiles
```
Wir erzeugen eine 200×3-Matrix von Zufallszahlen
We generate a 200×3 matrix of random numbers
```{julia}
A = rand(200,3)
```
und speichern diese
and save it
```{julia}
f = open("data2.txt", "w")
writedlm(f, A)
@@ -366,23 +380,23 @@ close(f)
```
Die geschriebene Datei fängt so an:
The written file starts like this:
```{julia}
;head data2.txt
```
Das Wiedereinlesen ist noch einfacher:
Reading it back is even simpler:
```{julia}
B = readdlm("data2.txt")
```
Noch ein Punkt: Beim Umgang mit Dateien wird in Julia oft die `do`-Notation verwendet, s. @sec-do.
Dazu nutzt man, dass `open()` auch Methoden hat, bei denen das 1. Argument eine `function(iostream)` ist.
Diese wird dann auf den _stream_ angewendet und dieser abschliessend automatisch geschlossen. Die `do`-Notation erlaubt es,
diese Funktion anonym nach dem `do` zu definieren:
One more point: In Julia, the `do` notation is often used for file handling, see @sec-do.
This uses the fact that `open()` also has methods where the 1st argument is a `function(iostream)`.
This function is then applied to the _stream_ and the stream is automatically closed at the end. The `do` notation allows you to
define this function anonymously after the `do`:
```{julia}
open("data2.txt", "w") do io
@@ -390,18 +404,16 @@ open("data2.txt", "w") do io
end
```
### CSV und DataFrames
- Das CSV-Format wird oft benutzt, um Tabellen in einer nicht nur mit MS Excel lesbaren Form zur Verfügung zu stellen.
- Ein Beispiel ist die Wetter- und Klimadatenbank _Meteostat_.
- Das Paket [DataFrames.jl](https://dataframes.juliadata.org/stable/) stellt Funktionen zum bequemen Umgang mit tabellarischen Daten
zur Verfügung.
### CSV and DataFrames
- The CSV format is often used to provide tables in a form that can be read not only by MS Excel.
- An example is the weather and climate database _Meteostat_.
- The [DataFrames.jl](https://dataframes.juliadata.org/stable/) package provides functions for convenient handling of tabular data.
```{julia}
using CSV, DataFrames, Downloads
# Wetterdaten von Westerland, s. https://dev.meteostat.net/bulk/hourly.html
# Weather data from Westerland, see https://dev.meteostat.net/bulk/hourly.html
url = "https://bulk.meteostat.net/v2/hourly/10018.csv.gz"
http_response = Downloads.download(url)
@@ -409,25 +421,26 @@ file = CSV.File(http_response, header=false);
```
Die Daten sehen so aus:
The data looks like this:
```{julia}
# https://dev.meteostat.net/bulk/hourly.html#endpoints
#
# Spalte 1 Datum
# 2 Uhrzeit (Stunde)
# 3 Temp
# 5 Luftfeuchtigkeit
# 6 Niederschlag
# 8 Windrichtung
# 9 Windstärke
# Column 1 Date
# 2 Time (hour)
# 3 Temperature
# 5 Humidity
# 6 Precipitation
# 8 Wind direction
# 9 Wind speed
df = DataFrame(file)
```
```{julia}
#| error: false
#| echo: false
@@ -438,18 +451,19 @@ describe(df)
Zum bequemen Plotten und zum Umgang mit den Datums- und Zeitformaten in der Wettertabelle
laden wir noch 2 Helferlein:
For convenient plotting and handling of date and time formats in the weather table,
we load two helper packages:
```{julia}
using StatsPlots, Dates
```
Wir erzeugen eine neue Spalte, die Datum (aus Spalte 1) und Uhrzeit (aus Spalte 2) kombiniert:
We create a new column that combines date (from column 1) and time (from column 2):
```{julia}
# neue Spalte mit Sp.1 und 2 (date & time) kombiniert
# new column combining col. 1 and 2 (date & time)
df[!, :datetime] = DateTime.(df.Column1) .+ Hour.(df.Column2);
```
@@ -466,14 +480,12 @@ df[!, :datetime] = DateTime.(df.Column1) .+ Hour.(df.Column2);
@df df plot(:datetime, :Column3)
```
Und nun zum Plot:
And now to the plot:
```{julia}
@df df plot(:datetime, [:Column9, :Column6, :Column3],
xlims = (DateTime(2023,9,1), DateTime(2024,5,30)),
layout=(3,1), title=["Wind" "Regen" "Temp"],
layout=(3,1), title=["Wind" "Rain" "Temp"],
legend=:none, size=(800,800))
```