Skip to content

Commit f4e0829

Browse files
authored
Traduction chapitre regex (#539)
* Up * up * up * up * remove
1 parent 783a278 commit f4e0829

9 files changed

Lines changed: 846 additions & 580 deletions

File tree

‎_quarto.yml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ project:
55
- index.qmd
66
- content/getting-started/index.qmd
77
- content/manipulation/index.qmd
8-
- content/manipulation/04c_API_TP.qmd
8+
- content/manipulation/04b_regex_TP.qmd
99
- content/visualisation/index.qmd
1010
- content/modelisation/index.qmd
1111
- content/NLP/index.qmd
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
::: {.content-visible when-profile="fr"}
2+
3+
::: {.exercise}
4+
## Exercice 1
5+
6+
1. On va d'abord s'occuper d'extraire le jour de naissance.
7+
+ Le premier chiffre du jour est 0, 1, 2 ou 3. Traduire cela sous la forme d'une séquence `[X-X]`
8+
+ Le deuxième chiffre du jour est lui entre 0 et 9. Traduire cela sous la séquence adéquate
9+
+ Remarquez que le premier jour est facultatif. Intercaler entre les deux classes de caractère adéquate
10+
le quantifieur qui convient
11+
+ Ajouter le slash à la suite du motif
12+
+ Tester avec `re.findall`. Vous devriez obtenir beaucoup plus d'échos que nécessaire.
13+
C'est normal, à ce stade la
14+
regex n'est pas encore finalisée
15+
2. Suivre la même logique pour les mois en notant que les mois du calendrier grégorien ne dépassent
16+
jamais la première dizaine. Tester avec `re.findall`
17+
3. De même pour les années de naissance en notant que jusqu'à preuve du contraire, pour des personnes vivantes
18+
aujourd'hui, les millénaires concernés sont restreints. Tester avec `re.findall`
19+
4. Cette regex n'est pas naturelle, on pourrait très bien se satisfaire de classes de
20+
caractères génériques `\d` même si elles pourraient, en pratique, nous sélectionner des
21+
dates de naissance non possibles (`43/78/4528` par exemple). Cela permettrait
22+
d'alléger la regex afin de la rendre plus intelligible. Ne pas oublier l'utilité des quantifieurs.
23+
5. Comment adapter la regex pour qu'elle soit toujours valide pour nos cas mais permette aussi de
24+
capturer les dates de type `YYYY/MM/DD` ? Tester sur `1998/07/12`
25+
26+
27+
:::
28+
29+
:::
30+
31+
::: {.content-visible when-profile="en"}
32+
33+
::: {.exercise}
34+
## Exercise 1
35+
36+
1. First, extract the day of birth.
37+
+ The first digit of the day is 0, 1, 2, or 3. Translate this into a `[X-X]` sequence.
38+
+ The second digit of the day is between 0 and 9. Translate this into the appropriate sequence.
39+
+ Note that the first digit of the day is optional. Insert the appropriate quantifier between the two character classes.
40+
+ Add the slash after the pattern.
41+
+ Test with `re.findall`. You should get many more matches than needed. This is normal; at this stage, the regex is not yet finalized.
42+
2. Follow the same logic for the months, noting that Gregorian calendar months never exceed the first dozen. Test with `re.findall`.
43+
3. Do the same for the birth years, noting that, unless proven otherwise, for people alive today, the relevant millennia are limited. Test with `re.findall`.
44+
4. This regex is not natural; one could be satisfied with generic character classes `\d`, even though they might practically select impossible birth dates (e.g., `43/78/4528`). This would simplify the regex, making it more readable. Don’t forget the usefulness of quantifiers.
45+
5. How can the regex be adapted to always be valid for our cases but also capture dates of the type `YYYY/MM/DD`? Test with `1998/07/12`.
46+
47+
:::
48+
49+
:::
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
```{python}
2+
#| output: false
3+
exo1_q1 = re.findall("[0-3]?[0-9]/", s)
4+
```
5+
6+
```{python}
7+
#| output: false
8+
exo1_q2 = re.findall("[0-3]?[0-9]/[0-1]?[0-9]", s)
9+
```
10+
11+
```{python}
12+
#| output: false
13+
# Question 3
14+
exo1_q3 = re.findall(
15+
"[0-3]?[0-9]/[0-1]?[0-9]/[0-2]?[0-9]?[0-9][0-9]", s
16+
)
17+
```
18+
19+
```{python}
20+
#| output: false
21+
# Question 4
22+
exo1_q4 = re.findall("\d{1,2}/\d{1,2}/\d{2,4}", s)
23+
```
24+
25+
```{python}
26+
#| output: false
27+
# Question 5
28+
exo1_q5 = re.findall(
29+
"\d{1,4}/\d{1,2}/\d{1,4}", s + "\n 1998/07/12"
30+
)
31+
```
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
::: {.content-visible when-profile="fr"}
2+
:::: {.exercise}
3+
## Exercice 2: extraction d'adresses email
4+
5+
Utiliser la structure d'une adresse mail `[XXXX]@[XXXX]` pour récupérer
6+
ce contenu
7+
8+
::::
9+
:::
10+
11+
::: {.content-visible when-profile="en"}
12+
:::: {.exercise}
13+
## Exercise 2: Extracting email addresses
14+
15+
Use the structure of an email address `[XXXX]@[XXXX]` to retrieve this content.
16+
17+
::::
18+
:::
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
```{python}
2+
#| echo: false
3+
#| output: false
4+
5+
# \S` represents any non-space character
6+
# `+` denotes the presence of the preceding set of characters between 1 and infinity
7+
list_emails = re.findall('\S+@\S+', text_emails)
8+
```
9+
10+
```{python}
11+
#| echo: false
12+
list_emails
13+
```
Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
::: {.content-visible when-profile="fr"}
2+
:::: {.exercise}
3+
## Exercice 3
4+
5+
La base en question contient des livres de la British Library et quelques informations les concernant. Le jeu de données est disponible ici : https://raw.githubusercontent.com/realpython/python-data-cleaning/master/Datasets/BL-Flickr-Images-Book.csv
6+
7+
La colonne "Date de Publication" n'est pas toujours une année, il y a parfois d'autres informations. Le but de l'exercice est d'avoir **une date de publication du livre propre** et de regarder la **distribution des années de publications**.
8+
9+
Pour ce faire, vous pouvez :
10+
11+
* Soit choisir de réaliser l'exercice sans aide. Votre **lecture de l'énoncé s'arrête donc ici**. Vous devez alors faire attention à bien regarder vous-même la base de données et la transformer avec attention.
12+
13+
* Soit suivre les différentes étapes qui suivent pas à pas.
14+
15+
```{=html}
16+
<details><summary>Version guidée 👇</summary>
17+
```
18+
19+
1. Lire les données depuis l'url `https://raw.githubusercontent.com/realpython/python-data-cleaning/master/Datasets/BL-Flickr-Images-Book.csv`. Attention au séparateur
20+
2. Ne garder que les colonnes `['Identifier', 'Place of Publication', 'Date of Publication', 'Publisher', 'Title', 'Author']`
21+
3. Observer la colonne _'Date of Publication'_ et remarquer le problème sur certaines lignes (par exemple la ligne 13)
22+
4. Commencez par regarder le nombre d'informations manquantes. On ne pourra pas avoir mieux après la regex, et normalement on ne devrait pas avoir moins...
23+
5. Déterminer la forme de la regex pour une date de publication. A priori, il y a 4 chiffres qui forment une année.
24+
Utiliser la méthode `str.extract()` avec l'argument `expand = False` (pour ne conserver que la première date concordant avec notre _pattern_)?
25+
6. On a 2 `NaN` qui n'étaient pas présents au début de l'exercice. Quels sont-ils et pourquoi ?
26+
7. Quelle est la répartition des dates de publications dans le jeu de données ? Vous pouvez par exemple afficher un histogramme grâce à la méthode `plot` avec l'argument `kind ="hist"`.
27+
28+
```{=html}
29+
</summary>
30+
```
31+
32+
::::
33+
:::
34+
35+
::: {.content-visible when-profile="en"}
36+
:::: {.exercise}
37+
## Exercise 3
38+
39+
The dataset in question contains books from the British Library and some related information. The dataset is available here: https://raw.githubusercontent.com/realpython/python-data-cleaning/master/Datasets/BL-Flickr-Images-Book.csv
40+
41+
The "Date of Publication" column is not always a year; sometimes there are other details. The goal of the exercise is to have **a clean book publication date** and to examine the **distribution of publication years**.
42+
43+
To do this, you can:
44+
45+
* Either choose to perform the exercise without help. Your **reading of the instructions ends here**. You should carefully examine the dataset and transform it yourself.
46+
47+
* Or follow the step-by-step instructions below.
48+
49+
```{=html}
50+
<details><summary>Guided version 👇</summary>
51+
```
52+
53+
1. Read the data from the URL `https://raw.githubusercontent.com/realpython/python-data-cleaning/master/Datasets/BL-Flickr-Images-Book.csv`. Be careful with the separator.
54+
2. Keep only the columns `['Identifier', 'Place of Publication', 'Date of Publication', 'Publisher', 'Title', 'Author']`.
55+
3. Observe the _'Date of Publication'_ column and note the issues with some rows (e.g., row 13).
56+
4. Start by looking at the number of missing values. We cannot do better after regex, and normally we should not have fewer...
57+
5. Determine the regex pattern for a publication date. Presumably, there are 4 digits forming a year. Use the `str.extract()` method with the `expand = False` argument (to keep only the first date matching our pattern)?
58+
6. We have 2 `NaN` values that were not present at the start of the exercise. What are they and why?
59+
7. What is the distribution of publication dates in the dataset? You can, for example, display a histogram using the `plot` method with the `kind = "hist"` argument.
60+
61+
```{=html}
62+
</summary>
63+
```
64+
65+
::::
66+
:::
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
```{python}
2+
# Question 1
3+
data_books = pd.read_csv('https://raw.githubusercontent.com/realpython/python-data-cleaning/master/Datasets/BL-Flickr-Images-Book.csv',sep=',')
4+
```
5+
6+
```{python}
7+
# Question 2
8+
data_books = data_books.loc[
9+
:,
10+
['Identifier', 'Place of Publication', 'Date of Publication', 'Publisher', 'Title', 'Author']
11+
]
12+
```
13+
14+
::: {.content-visible when-profile="fr"}
15+
Voici par exemple le problème qu'on demande de détecter à la question 3 :
16+
:::
17+
::: {.content-visible when-profile="en"}
18+
Here is an example of the problem to detect in question 3:
19+
:::
20+
21+
22+
```{python}
23+
# Question 3
24+
(
25+
data_books
26+
.loc[: , ['Date of Publication',"Title"]]
27+
.iloc[13:20]
28+
)
29+
```
30+
31+
::: {.content-visible when-profile="fr"}
32+
A la question 4, on obtient la réponse
33+
:::
34+
::: {.content-visible when-profile="en"}
35+
Question 4 answer should be
36+
:::
37+
38+
39+
```{python}
40+
# Question 4
41+
data_books['Date of Publication'].isna().sum()
42+
```
43+
44+
```{python}
45+
# Question 5
46+
expression = "([0-2][0-9][0-9][0-9])"
47+
data_books['year'] = (
48+
data_books['Date of Publication']
49+
.str.extract(expression, expand=False)
50+
)
51+
52+
answer_q5 = (
53+
data_books
54+
.loc[
55+
~(data_books['Date of Publication'] == data_books['year']),
56+
['Date of Publication', 'year']
57+
]
58+
)
59+
```

0 commit comments

Comments
 (0)