Table Of ContentОСНОВЫ ПРОГРАММИРОВАНИЯ В PYTHON: ТРИ В ОДНОМ
Названия фруктов, отсортированных в порядке возрастания:
Авокадо 156.5
Ананас 170.0
Апельсин 120.0
0
ОГЛАВЛЕНИЕ
Министерство науки и высшего образования Российской Федерации
Федеральное государственное бюджетное образовательное учреждение
высшего образования
«Владимирский государственный университет
имени Александра Григорьевича и Николая Григорьевича Столетовых»
Ф. Ж. ТАННИНГ
F. `J. TANGNING
ОСНОВЫ ПРОГРАММИРОВАНИЯ
В PYTHON: ТРИ В ОДНОМ
THE BASICS OF PYTHON
PROGRAMMING: THREE IN ONE
Учебное пособие (The course book)
Электронное издание (Electronic publication)
В четырех томах (In four volumes)
Том 2 (Volume II)
Владимир 2022
1
ОСНОВЫ ПРОГРАММИРОВАНИЯ В PYTHON: ТРИ В ОДНОМ
УДК 004.432
ББК 32.973.2
Рецензенты:
Кандидат технических наук, доцент
доцент кафедры информационных систем
Тюменского государственного университета
Ю. Е. Карякин
Доктор технических наук, профессор
зав. кафедрой информационных систем и программной инженерии
Владимирского государственного университета
имени Александра Григорьевича и Николая Григорьевича Столетовых
И. Е. Жигалов
Таннинг Ж., Ф.
Основы программирования в Python: три в одном [Электронный
ресурс] : учеб. пособие. В 4 т. Т. 2 / Ф. Ж. Таннинг ; Владим. гос. ун-т им.
А. Г. и Н. Г. Столетовых. – Владимир : Изд-во ВлГУ, 2022. – 472 с. – ISBN
978-5-9984-1361-2 (т. 2). – ISBN 978-5-9984-1227-1. ‒ Электрон. дан. (8,92
Мб). – 1 электрон. опт. диск (CD-ROM). – Систем. требования: Intel от 1,3
ГГц ; Windows XP/7/8/10/11, Linux, Mac OS ; Adobe Reader ; дисковод CD-
ROM. ‒ Загл. с титул. экрана.
В книге описывается процесс программирования на языке Python c использованием
практических примеров и упражнений. Цель пособия состоит в том, чтобы научиться
программировать индивидуально в определенных научных областях: обработка файлов,
анализ данных с помощью библиотеки Pandas и др. Обучающий материал пособия также
дает возможность иностранным студентам освоить дисциплину, преодолевая языковой
барьер. Студенты, владеющие русским языком, могут совершенствовать свои знания на
французском и английском благодаря синхронизации материала, представленного на этих
языках.
Издание рекомендовано для студентов различных технических направлений,
преподавателям вузов и всем, кто начинает делать свои первые шаги в программировании,
используя язык Python в качестве инструмента программирования.
Рекомендовано для формирования общепрофессиональных компетенций в
соответствии с ФГОС ВО.
Табл. 93. Ил. 39. Библиогр.: 19 назв.
УДК 004.432
ББК 32.973.3
ISBN 978-5-9984-1361-2 (т. 2) © ВлГУ, 2022
ISBN 978-5-9984-1227-1
2
ОГЛАВЛЕНИЕ
UDC 004.432
BBK 32.973.2
Reviewers:
Candidate of Technical Sciences, Associate Professor
Associate Professor of the Department of Information Systems
of Tyumen State University
Yu. E. Karyakin
Doctor of Technical Sciences, Professor
Head of the Department of Information Systems and Software Engineering
of Vladimir State University named after Alexander and Nikolai Stoletovs
I. E. Zhigalov
Tangning J., F.
The basics of python programming: three in one [Electronic resource] :
the course book. In 4 vol. Vol. 2 / F. J. Tangning ; Vladimir State University
named after Alexander and Nikolai Stoletovs. – Vladimir : Publishing house
VlSU, 2022. – 472 p. – ISBN 978-5-9984-1361-2 (vol. 2). – ISBN 978-5-
9984-1227-1. ‒ Electronшс data (8.92 MB). – 1 optical disk (CD-ROM). –
Systems Requirements: CPU Intel from 1.3 GHz; Windows XP/7/8/10/11,
Linux, Mac OS ; Adobe Reader; CD-ROM drive. ‒ Name from the title
screen.
The course book describes the process of programming in Python language using
practical examples and exercises. The goal of the manual is to learn to program individually in
certain scientific fields: file processing, data analysis using the Pandas library, etc. The teaching
material in the book enables foreign (non-Russian) students to master the discipline by
overcoming the language barrier. Students who already speak Russian can improve their
knowledge of French and English through the synchronization of the material presented in these
languages.
The publication is recommended for students of various technical fields, teachers and
anyone who is starting to take their first steps in programming, using the Python language as a
programming tool.
It is also recommended for the acquisition of general professional skills in accordance
with the higher education standards of the Russian Federation.
Tabl. 93. Il. 39. Bibliogr.: 19 titl.
UDC 004.432
BBK 32.973.2
ISBN 978-5-9984-1361-2 (vol. 2) © VlSU, 2022
ISBN 978-5-9984-1227-1
3
ОСНОВЫ ПРОГРАММИРОВАНИЯ В PYTHON: ТРИ В ОДНОМ
RU СПИСОК ОСНОВНЫХ СОКРАЩЕНИЙ
EN MAIN ABBREVIATIONS
FR LES PRINCIPALES ABRÉVIATIONS
RU – означает, что за этой частью главы на русском языке следует
перевод на английский и французский языки
EN – означает, что за этой частью главы на английском языке следует
перевод на русский и французский языки
FR – означает, что за этой частью главы на французском языке следует
перевод на русский и английский языки
RU – means that this part of the chapter in Russian is followed by a
translation into English and French
EN – means that this part of the chapter in English is followed by a
translation into Russian and French
FR – means that this part of the chapter in French is followed by a
translation into Russian and English
RU – signifie que cette partie du chapitre en russe est suivie d’une
traduction en anglais et en français
EN – signifie que cette partie du chapitre en anglais est suivie d’une
traduction en russe et en français
FR – signifie que cette partie du chapitre en français est suivie d’une
traduction en russe et en anglais
4
ОГЛАВЛЕНИЕ
ОГЛАВЛЕНИЕ
RU ПРЕДИСЛОВИЕ ................................................................................ 10
RU ВВЕДЕНИЕ ........................................................................................ 22
RU Глава I. ЧТЕНИЕ, ЗАПИСЬ И ДРУГИЕ ДЕЙСТВИЯ В ФАЙЛЕ 28
RU Введение ......................................................................................... 28
RU I.1. Создание объекта для управления файлом ........................... 29
RU I.2. Чтение файла ............................................................................ 32
RU I.3. Сохранение данных в файл .................................................... 35
RU I.4. Заключительные действия над файлом после его
использования ....................................................................................... 38
RU I.5. Вопросы о понимании курса .................................................. 47
RU Глава II. ВЗАИМОДЕЙСТВИЕ С PDF ФАЙЛАМИ В PYTHON 85
RU II.1. Библиотека PDFplumber – чтение и/или запись в PDF-файл
................................................................................................................. 85
RU II.2. Библиотека PDFminer.six – чтение и / или запись в PDF-
файл ........................................................................................................ 86
RU Глава III. ОБРАБОТКА СТРОК В PYTHON ................................ 137
RU Введение ....................................................................................... 137
RU III.1. Процесс кодирования символов ........................................ 137
RU III.2. Управление клавиатурой компьютера .............................. 139
RU III.3. Манипулирование компьютерной мышью ...................... 158
RU III.4. Как определить кодировку текстового файла.................. 164
RU III.5. Как определить кодировку веб-страницы ........................ 170
RU III.5.1. Представление кодировки на веб-странице .............. 170
RU III.5.2. Определение кодировки веб-страницы с помощью
кода ................................................................................................... 172
RU Глава IV. АЛГОРИТМЫ СОРТИРОВКИ ..................................... 253
RU Введение ....................................................................................... 253
RU IV.1. Схематическое описание некоторых алгоритмов
сортировки ........................................................................................... 254
RU IV.2. Сортировка по кучам или сортировка по пирамидам (на
англ. heapsort) ...................................................................................... 260
5
ОСНОВЫ ПРОГРАММИРОВАНИЯ В PYTHON: ТРИ В ОДНОМ
RU IV.3. Описание алгоритма быстрой сортировки и сортировки
слиянием .............................................................................................. 262
RU IV.4. Вопросы и задачи ............................................................... 264
RU Глава V. PANDAS – ИНСТРУМЕНТ АНАЛИЗА ДАННЫХ ..... 291
RU V.1. Pandas в «Series» ................................................................... 292
RU V.2. Передача данных из одномерного массива (Series) в файл
разных форматов ................................................................................. 311
RU V.3. Другие методы с использованием «Series» ....................... 314
RU V.4. Pandas в двумерном массиве – DataFrame ......................... 319
RU V.4.1. Хранение и вставка данных ......................................... 319
RU V.4.2 Возможные операции с четко определенным столбцом
........................................................................................................... 323
RU V.4.3 Некоторые операции и взаимодействия между Excel и
Pandas ............................................................................................... 328
RU V.5. Упражнения на Pandas ......................................................... 342
RU V.6. Ответы на задания в Pandas ................................................ 344
RU V.7. Вопросы ................................................................................ 349
RU ЗАКЛЮЧЕНИЕ ................................................................................ 465
СПИСОК ИСПОЛЬЗОВАННОЙ И РЕКОМЕНДУЕМОЙ
ЛИТЕРАТУРЫ ........................................................................................ 468
TABLE OF CONTENTS
EN PREFACE ............................................................................................ 14
EN INTRODUCTION ............................................................................... 24
EN CHAPTER I. READING, WRITING AND OTHER ACTIONS IN
THE FILE ................................................................................................... 48
EN Introduction ...................................................................................... 48
EN I.1. Creating an object to manage the file ........................................ 49
EN I.2. Reading a file ............................................................................. 51
EN I.3. Saving data to a file ................................................................... 54
EN I.4. The final actions on the file after its use .................................... 57
EN I.5. Questions about understanding the course ................................ 66
EN Chapter II. INTERACTION WITH PDF FILES IN PYTHON ........ 102
6
ОГЛАВЛЕНИЕ
EN II.1. PDFplumber Library – reading and/or writing to a PDF file . 102
EN II.2. PDFMiner.six library – reading and/or writing to a PDF file 103
EN Chapter III. ROW PROCESSING IN PYTHON .............................. 177
EN Introduction .................................................................................... 177
EN III.1. The process of encoding characters ...................................... 177
EN III.2. Computer keyboard control .................................................. 179
EN III.3. Manipulating a computer mouse ........................................... 196
EN III.4. How to determine the encoding of a text file ....................... 202
EN III.5. How to determine the encoding of a web page ..................... 208
EN III.5.1. Encoding representation on a web page ......................... 208
EN III.5.2. Determining the encoding of a web page using code .... 210
EN Chapter IV. SORTING ALGORITHMS ........................................... 266
EN Introduction .................................................................................... 266
EN IV.1. Schematic description of some sorting algorithms ............... 267
EN IV.2. Sorting by heaps (heapsort) or sorting by pyramids ............. 273
EN IV.3. Description of the algorithm for quick sorting and merge
sorting ................................................................................................... 274
EN IV.4. Questions and exercises ........................................................ 276
EN Chapter V. PANDAS – A DATA ANALYSIS TOOL ..................... 351
EN 5.1. Pandas in «Series» .................................................................. 352
EN V.2. Transferring data from a one-dimensional array (Series) to a
file of different formats ......................................................................... 370
EN V.3. Other methods using «Series» ................................................ 373
EN V.4. Pandas in a two-dimensional array – DataFrame .................. 378
EN V.4.1. Storing and inserting data ................................................ 378
EN V.4.2 Possible operations with a well-defined column .............. 382
EN V.4.3 Some operations and interactions between Excel and Pandas
........................................................................................................... 386
EN V.5. Exercises on Pandas ............................................................... 400
EN V.6. Answers to exercises on Pandas ............................................. 402
EN V.7. Questions ................................................................................ 405
EN CONCLUSION .................................................................................. 466
LIST OF LITERATURES USED AND RECOMMENDED .................. 468
7
ОСНОВЫ ПРОГРАММИРОВАНИЯ В PYTHON: ТРИ В ОДНОМ
TABLE DES MATIÈRES
FR LA PRÉFACE ...................................................................................... 18
FR INTRODUCTION ................................................................................ 26
FR Chapitre I. LIRE, ÉCRIRE ET AUTRES ACTIONS DANS LE
FICHIER ..................................................................................................... 67
FR Introduction....................................................................................... 67
FR I.1. Création de l'objet pour la manipulation d’un fichier ................ 68
FR I.2. Lecture du fichier ....................................................................... 71
FR I.3. L’enregistrement des données dans un fichier ........................... 73
FR I.4. Les actions finales sur le fichier après son utilisation ............... 76
FR I.5. Questions de compréhension du cours ....................................... 84
FR Chapitre II. INTERACTION AVEC LES FICHIERS PDF DANS
PYTHON .................................................................................................. 119
FR II.1. La bibliotheque PDFplumber – lire et/ou écrire dans un fichier
PDF ....................................................................................................... 119
FR II.2. La bibliotheque PDFminer.six – lire et/ou écrire dans un fichier
PDF ....................................................................................................... 120
FR Chapitre III. TRAITEMENT DE LA CHAÎNE EN PYTHON ......... 215
FR Introduction..................................................................................... 215
FR III.1. Le processus du codage des caractères ................................. 215
FR III.2. Manipulation du clavier d’un ordinateur ............................... 217
FR III.3. Manipulation de la souris d’un ordinateur ............................ 234
FR III.4. Comment déterminer l'encodage d'un fichier texte ............... 240
FR III.5. Comment déterminer l'encodage d’une page web ................ 246
FR III.5.1. Représentation de l’encodage dans une page Web ........ 246
FR III.5.2. Détermination par code de l'encodage d’une page web . 248
FR Chapitre IV. ALGORITHMES DE TRI ............................................ 278
FR Introduction..................................................................................... 278
FR IV.1. Description schématique de certains algorithmes tri ............ 279
FR IV.2 Le tri par tas ou tri Pyramidal (en anglais : heapsort) ............ 285
FR IV.3. Description de l’algorithme tri rapide et tri par fusion ......... 287
8
ОГЛАВЛЕНИЕ
FR IV.4. Questions et exercices ........................................................... 289
FR Chapitre V. PANDAS – OUTIL D’ANALYSE DE DONNÉES ...... 407
FR 5.1. Pandas en série (Series) ........................................................... 408
FR V.2. Transfert de données d'un tableau unidimensionnel (Series)vers
un fichier à différents formats............................................................... 425
FR V.3. Les autres méthodes sur les «Series» ..................................... 428
FR V.4. Pandas en massive bidimensionnel - DataFrame ................... 433
FR V.4.1. Stockage et insertion des données ................................... 433
FR V.4.2 Les manœuvres possibles sur une colonne bien déterminée
........................................................................................................... 437
FR V.4.3 Quelques opérations et interactions entre Excel et Pandas
........................................................................................................... 441
FR V.5. Exercices sur Pandas .............................................................. 456
FR V.6. Réponses aux exercices sur Pandas ........................................ 459
FR V.7. Questions de compréhension .................................................. 463
FR CONCLUSION .................................................................................. 467
LISTE DES MANUELS (SOURCES ) UTILISÉS ET RECOMMANDÉS
.................................................................................................................. 468
9