commit 17eeb0ccb81e67690cd1c036bdf0dad643c7b566 Author: Ilia Miheev Date: Tue Oct 21 21:09:30 2025 +0300 first commit diff --git a/.nojekyll b/.nojekyll new file mode 100644 index 0000000..e69de29 diff --git a/README.md b/README.md new file mode 100644 index 0000000..c577f3a --- /dev/null +++ b/README.md @@ -0,0 +1,5 @@ +### Сайт-документация к библиотеке ipars + +~ Навигация по разделам и заголовкам +~ Возможна смена темы (тёмная/светлая) +~ Доступна на двух языках (русский/английский) \ No newline at end of file diff --git a/_404.md b/_404.md new file mode 100644 index 0000000..6fadad4 --- /dev/null +++ b/_404.md @@ -0,0 +1,3 @@ +# Страница не найдена + +Вернись на [главную](/home.md) \ No newline at end of file diff --git a/_coverpage.md b/_coverpage.md new file mode 100644 index 0000000..2d2a6e8 --- /dev/null +++ b/_coverpage.md @@ -0,0 +1,16 @@ + + +![logo](./pinguin_png.png) + +# ipars 3.7.0 + +> Библиотека для работы с файлами во время парсинга + + +- Работает с html, json, csv +- Улучшает UX с помощью прогресс-баров +- Позволяет засекать время работы скрипта +- Архивирует данные по завершении работы + +[GitHub](https://github.com/IliaMiheev/ipars) +[Get Started](#Библиотека-для-работы-с-файлами-во-время-парсинга) diff --git a/_navbar.md b/_navbar.md new file mode 100644 index 0000000..bc55449 --- /dev/null +++ b/_navbar.md @@ -0,0 +1,9 @@ + + +* Languages + + * [Русский](./home.md) + * [English](./pages/en/README_EN.md) + +* [GitHub](https://github.com/IliaMiheev/ipars) +* [Pypi](https://pypi.org/project/ipars/) diff --git a/_sidebar.md b/_sidebar.md new file mode 100644 index 0000000..324222e --- /dev/null +++ b/_sidebar.md @@ -0,0 +1,15 @@ + + +* [**Главная**](./home.md) + +* [**Pars**](./pages/ru/Pars_RU.md) + +* [**JsonManager**](./pages/ru/JsonManager_RU.md) + +* [**CsvManager**](./pages/ru/CsvManager_RU.md) + +* [**ProgressBar**](./pages/ru/ProgressBarManager_RU.md) + +* [**TimerManager**](./pages/ru/TimerManager_RU.md) + +* [**ZipManager**](./pages/ru/ZipManager_RU.md) diff --git a/favicon.ico b/favicon.ico new file mode 100644 index 0000000..5704ad2 Binary files /dev/null and b/favicon.ico differ diff --git a/home.md b/home.md new file mode 100644 index 0000000..58fea9a --- /dev/null +++ b/home.md @@ -0,0 +1,27 @@ +## Библиотека для работы с файлами во время парсинга {docsify-ignore-all} + +Во время парсинга часто приходится скачивать html-страницы, работать с json- и csv-файлами. Эта библиотека призвана облегчить написание кода для такого рода задач, а так же предоставляет ряд дополнительных возможностей. + +### В библиотеке есть три класса для основных работ + +1. **Pars** для работы с запросами и bs4 +2. **JsonManager** для работы с json +3. **CsvManager** для работы с csv + +### Так же есть три вспомогательных класса + +1. **ProgressBarManager** для создания прогресс-баров +2. **TimerManager** для засечения времени выполнения определённого кода +3. **ZipManager** для архивации файлов и папок + +### Установить библиотеку: + +```bash +pip install ipars +``` + +или + +```bash +pip3 install ipars +``` diff --git a/index.html b/index.html new file mode 100644 index 0000000..c20c6e2 --- /dev/null +++ b/index.html @@ -0,0 +1,94 @@ + + + + + + Документация ipars + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Секундочку...
+ + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/pages/en/CsvManager_EN.md b/pages/en/CsvManager_EN.md new file mode 100644 index 0000000..7ae688c --- /dev/null +++ b/pages/en/CsvManager_EN.md @@ -0,0 +1,45 @@ +### Working with CsvManager + +This class is designed to write and extract information from csv files + +The CsvManager class takes three arguments: the newline character newline (default is an empty string), the encoding of the opened files encoding (default is UTF-8), and the delimiter used in the CSV file delimiter (default is ";"). + +```py + +from ipars import CsvManager + +c = CsvManager() +``` + +### Brief Overview of CsvManager Methods + +1. The **writerow** method writes a row to the CSV file. The method takes the path to the CSV file, the write mode, and a list of data that will be written to the file's row. + +2. The **writerows** method takes the same arguments as writerow, but the row must be a double list with data for writing. The difference between these methods is that writerow writes one row, while writerows writes as many as there are in the double list. + +3. The **getRows** method is used to retrieve a list of rows in the CSV file. The method takes the path to the file from which the rows will be obtained. + +4. The **pprint** method is the same as that of Pars. + +### Example of Using CsvManager + +```py +from ipars import CsvManager +c = CsvManager() + +# writing headers +writer = c.writerow('./data.csv', 'w', ['Quantity', 'Price', 'Total']) + +# writing data +writer = c.writerows('./data.csv', 'a', [ +["5", "5", "25"], +["6", "6", "36"], +["7", "7", "49"], +]) + +# retrieving rows from the table +rows = c.getRows('./data.csv') + +# printing table rows +c.pprint(rows) +``` diff --git a/pages/en/JsonManager_EN.md b/pages/en/JsonManager_EN.md new file mode 100644 index 0000000..4a60786 --- /dev/null +++ b/pages/en/JsonManager_EN.md @@ -0,0 +1,34 @@ +### Working with JsonManager + +This class is designed to write and extract information from json files. + +JsonManager takes only one argument — the encoding in which the files will be read. The default is UTF-8. + +```py +from ipars import JsonManager + +j = JsonManager() +``` + +### Brief Overview of JsonManager Methods + +1. The **load** method is used to retrieve data from a JSON file at the specified path. + +2. The **dump** method is used to write data to a JSON file. It takes the path to the file and the data to be written. + +3. The **pprint** method is the same as that of Pars. + +### Example of Using JsonManager + +```py + +from ipars import JsonManager +j = JsonManager() + +# Writing data +j.dump('./data.json', [1, 2, 3, 4, 5, 6, 7]) + +# Retrieving data +data = j.load('./data.json') +j.pprint(data) # [1, 2, 3, 4, 5, 6, 7] +``` diff --git a/pages/en/Pars_EN.md b/pages/en/Pars_EN.md new file mode 100644 index 0000000..c26451d --- /dev/null +++ b/pages/en/Pars_EN.md @@ -0,0 +1,78 @@ +### Working with Pars + +This class is designed to work with requests and the resulting html page. + +The Pars class does not take any arguments for its constructors. + +```python +from ipars import Pars + +p = Pars() +``` + +### Brief Overview of Pars Methods + +1. The **getStaticPage** method takes the URL of the page, the path where the page will be saved, the write method, and request headers. The "wb" write method is used for saving images; by default, the write method is set to "w", which is used for HTML pages. If request headers are not specified, random user-agent headers will be used. The method returns the status response from the website, which should be used for conducting checks. +2. The **getDynamicPage** method uses the Selenium library to get a dynamically updated page. This is useful when content on the page loads dynamically. It takes the URL of the page, the save path, closeWindow, and timeSleep. By default, the Selenium browser opens in the background, and its operation is not visible, but if closeWindow is set to False, the code execution process will be shown. The timeSleep parameter can extend the page load time if content takes long to load. +3. The **gpsa** (get page semi-automatically) method is similar to the getDynamicPage method but works in a semi-automatic mode. It opens the webpage and waits until Enter is pressed in the terminal. During this time, you can register on the site and/or switch to the desired tab on the site, after which pressing Enter will allow the method to parse the page. This is suitable for social media feeds where unauthorized users have limited access to content. It accepts the same arguments and serves the same purposes as getDynamicPage, except for closeWindow. +4. The **returnBs4Object** method returns a BeautifulSoup object. It takes the path to the HTML page, converts its contents into a BeautifulSoup object, the file open encoding (default is UTF-8), and the parser type (default is lxml). +5. The **getAttributes** method is used to retrieve a list of attributes from a list of BeautifulSoup objects. It takes a list of BeautifulSoup objects and the name of the attribute to be extracted from the elements of the list. +6. The **getTexts** method is used to retrieve a list of text from a list of BeautifulSoup objects. It takes a list of BeautifulSoup objects and the needFix parameter. If this parameter is set to True, \n, \t, and spaces from the ends will be removed from the text. +7. The **pprint** method is used for displaying variable values that have a high level of nesting. For example, if you have an array of objects, where another array of objects is used as the value of a key. +8. The **mkdir** method is used to create a directory with the name nameDir if it does not already exist. + +### Example Parser Using ipars: + +```py +# Read about the ProgressBarManager class below +from ipars import Pars, ProgressBarManager +p = Pars() +nameFile = 'index.html' + +# Getting the HTML page +p.getDynamicPage(nameFile, 'https://duckduckgo.com/?q=greenhouse+social+technologies+youtube&iar=videos&atb=v454-1', closeWindow=0) + +# Getting the BeautifulSoup object +soup = p.returnBs4Object(nameFile) + +# Finding all answer cards +# The first results are those we want, while the rest are not. Therefore, we want the first 84 elements +allCards = soup.find*all(class*='b_NgmZrVnRtV8MZMEjLs')[:84] + +# Getting all images +allImg = [card.find('img') for card in allCards] + +# Getting all links +allSrc = p.getAttributes(allImg, 'src') + +# Creating the img folder if it doesn't already exist +nameFolder = 'img' +p.mkdir(nameFolder) + +# Creating a ProgressBarManager object +bar = ProgressBarManager(len(allSrc)) + +# Downloading images +for index, url in enumerate(allSrc): +url = 'https:' + url +p.getStaticPage(f'./{nameFolder}/img{index}.png', url, writeMethod='wb') +bar.next() +bar.finish() +``` + +### Example Using getAttributes and getTexts Methods + +```py +from ipars import Pars +p = Pars() + +p.getStaticPage('./index.html', 'https://google.com') +soup = p.returnBs4Object('./index.html') + +allTegA = soup.find_all('a') +a1 = p.getTexts(allTegA, needFix=1) +p.pprint(a1) + +a2 = p.getAttributes(allTegA, 'href') +p.pprint(a2) +``` diff --git a/pages/en/ProgressBarManager_EN.md b/pages/en/ProgressBarManager_EN.md new file mode 100644 index 0000000..b725944 --- /dev/null +++ b/pages/en/ProgressBarManager_EN.md @@ -0,0 +1,66 @@ +### Working with ProgressBarManager + +The class creates a progress bar for better visibility of code execution. It takes five arguments: + +1. **max**: a required parameter that indicates the maximum number of iterations in the progress bar. + +2. **message**: a message displayed before the progress bar. + +3. **color**: the color of the progress bar. + +4. **fill**: a character used to fill the completed portion. + +5. **width**: the size of the progress bar in characters. + +```py + +from ipars import ProgressBarManager + +bar = ProgressBarManager(100) # Here max is set to 100 +``` + +### Brief Overview of ProgressBarManager Methods + +1. The **next** method starts the next iteration of the progress bar. + +2. The **finish** method completes the progress bar. + +### Example of Using ProgressBarManager + +```py +# Importing libraries +from ipars import ProgressBarManager +from time import sleep + +maxValue = 300 + +# Creating a default progress bar +bar = ProgressBarManager(maxValue) + +# Simulating work +for _ in range(maxValue // 2): +sleep(0.1) +bar.next() + +# Turning off the progress bar +bar.finish() + +# Creating a more customized progress bar +bar = ProgressBarManager( +maxValue, +message='Downloading process', +color='red', +fill='\*', +width=50 +) + +# Simulating work + +for _ in range(maxValue): +sleep(0.1) +bar.next() + +# Turning off the progress bar + +bar.finish() +``` diff --git a/pages/en/README_EN.md b/pages/en/README_EN.md new file mode 100644 index 0000000..53d5843 --- /dev/null +++ b/pages/en/README_EN.md @@ -0,0 +1,27 @@ +### Library for File Handling During Parsing {docsify-ignore-all} + +During parsing, it is often necessary to download HTML pages and work with JSON and CSV files. This library is designed to simplify the coding tasks for such activities and provides a range of additional features. + +### The library contains three primary classes + +1. **Pars** for handling requests and bs4. +2. **JsonManager** for working with JSON. +3. **CsvManager** for handling CSV files. + +### There are also three auxiliary classes + +1. **ProgressBarManager** for creating progress bars. +2. **TimerManager** for measuring the execution time of specific code. +3. **ZipManager** for archiving files and folders. + +To install the library: + +```bash +pip install ipars +``` + +or + +```bash +pip3 install ipars +``` diff --git a/pages/en/TimerManager_EN.md b/pages/en/TimerManager_EN.md new file mode 100644 index 0000000..0a5332f --- /dev/null +++ b/pages/en/TimerManager_EN.md @@ -0,0 +1,35 @@ +### Working with TimerManager + +The TimerManager class is designed to track the execution time of code. It allows you to obtain the total runtime in various formats. + +```py +from ipars import TimerManager + +t = TimerManager() +``` + +### Brief Overview of TimerManager Methods + +1. The **start** method marks the starting point of the time measurement. + +2. The **end** method marks the endpoint of the time measurement. + +3. The **getWorkTime** method returns the total execution time in the specified format. Supported formats are seconds, minutes, and hours. The ndigits parameter specifies the number of decimal places for rounding; by default, the number is not rounded. + +### Example of Using TimerManager + +```py +from time import sleep +from ipars import TimerManager +t = TimerManager() + +# Starting the timer +t.start() +sleep(2) # simulating two seconds of work +t.end() + +# Displaying results in different formats +print(f"Execution time in seconds: {t.getWorkTime()}") # 2.0008320808410645 +print(f"Execution time in minutes: {t.getWorkTime(ndigits=2, format='minutes')}") # 0.03 +print(f"Execution time in hours: {t.getWorkTime(ndigits=4, format='hours')}") # 0.0006 +``` diff --git a/pages/en/ZipManager_EN.md b/pages/en/ZipManager_EN.md new file mode 100644 index 0000000..afc58ef --- /dev/null +++ b/pages/en/ZipManager_EN.md @@ -0,0 +1,33 @@ +### Working with ZipManager + +The ZipManager class is used for archiving a folder of files. It takes only one argument — the compression level for the files. + +'none' => No compression + +'normal' => Normal compression + +'hard' => Increased compression + +'maximum' => Maximum compression + +```py +from ipars import ZipManager + +z = ZipManager() +``` + +### Brief Overview of ZipManager Methods + +1. The **zip_file** method is used to archive a single file. It takes the path to the source file and the path to the output file. +2. The **zip_folder** method is used to archive a directory. It takes the path to the source directory and the path to the output file. + +### Example of Using ZipManager + +```py + +from ipars import ZipManager +z = ZipManager(compression='maximum') + +z.zip_file('./your_file.txt', 'file_archive_maximum.zip') +z.zip_folder('./your_folder/', 'folder_archive_maximum.zip') +``` diff --git a/pages/en/_sidebar.md b/pages/en/_sidebar.md new file mode 100644 index 0000000..eee0c93 --- /dev/null +++ b/pages/en/_sidebar.md @@ -0,0 +1,15 @@ + + +* [**Home**](./pages/en/README_EN.md) + +* [**Pars**](./pages/en/Pars_EN.md) + +* [**JsonManager**](./pages/en/JsonManager_EN.md) + +* [**CsvManager**](./pages/en/CsvManager_EN.md) + +* [**ProgressBar**](./pages/en/ProgressBarManager_EN.md) + +* [**TimerManager**](./pages/en/TimerManager_EN.md) + +* [**ZipManager**](./pages/en/ZipManager_EN.md) diff --git a/pages/ru/CsvManager_RU.md b/pages/ru/CsvManager_RU.md new file mode 100644 index 0000000..c13cc21 --- /dev/null +++ b/pages/ru/CsvManager_RU.md @@ -0,0 +1,45 @@ +### Работа с CsvManager + +Данный класс предназначен для записи и извлечения информации из csv-файлов. + + +Класс CsvManager принимает три аргумента: символ переноса на новую строку _newline_ (по умолчанию — это пустая строка), кодировку открываемых файлов _encoding_ (по умолчанию UTF-8) и разделитель который используется в csv файле _delimiter_ (по умолчанию ";") + +```py +from ipars import CsvManager + +c = CsvManager() +``` + +### Коротко о методах CsvManager + +1. Метод **writerow** записывает строку с csv файл. Метод принимает путь до csv файла, метод записи и список данных которые будут записанн в строку файла + +2. Метод **writerows** принимает теже самые аргументы что и writerow, только row должен быть двойным списком с данными для записи. Разница между этими методами в том что writerow записывает одну, а writerows столько сколько есть в двойном списке + +3. Метод **getRows** используется для получения списка строк в csv файле. Метод принимает путь до файла откуда будут получены строки + +4. Метод **pprint** такой же как и у Pars + +### Пример использования CsvManager + +```py +from ipars import CsvManager +c = CsvManager() + +# записываем заголовки +writer = c.writerow('./data.csv', 'w', ['Количество', 'Цена', 'Итог']) + +# записываем данные +writer = c.writerows('./data.csv', 'a', [ + ["5", "5", "25"], + ["6", "6", "36"], + ["7", "7", "49"], +]) + +# получаем строки из таблицы +rows = c.getRows('./data.csv') + +# выводим строки таблицы +c.pprint(rows) +``` diff --git a/pages/ru/JsonManager_RU.md b/pages/ru/JsonManager_RU.md new file mode 100644 index 0000000..f632ce9 --- /dev/null +++ b/pages/ru/JsonManager_RU.md @@ -0,0 +1,33 @@ +### Работа с JsonManager + +Данный класс предназначен для записи и извлечения информации из json-файлов. + +JsonManager принимает принимает только один аргумент — кодировку в которой будут читаться файлы. По умолчанию это UTF-8 + +```py +from ipars import JsonManager + +j = JsonManager() +``` + +### Коротко о методах JsonManager + +1. Метод **load** используется для получения данных из json-файла по указанному пути + +2. Метод **dump** используется для записи данных в json-файл. Принимает путь до файла и данные для записи + +3. Метод **pprint** такой же как и у Pars + +### Пример использования JsonManager + +```py +from ipars import JsonManager +j = JsonManager() + +# Записываем данные +j.dump('./data.json', [1, 2, 3, 4, 5, 6, 7]) + +# Получаем данные +data = j.load('./data.json') +j.pprint(data) # [1, 2, 3, 4, 5, 6, 7] +``` diff --git a/pages/ru/Pars_RU.md b/pages/ru/Pars_RU.md new file mode 100644 index 0000000..4bb2d1e --- /dev/null +++ b/pages/ru/Pars_RU.md @@ -0,0 +1,85 @@ +### Работа с Pars + +Данный класс предназначен для работы с запросами и полученной html-страницей. + +Класс Pars не принимает никаких данных для конструкторов. + +```python +from ipars import Pars + +p = Pars() +``` + +### Коротко о методах Pars: + +1. Метод **getStaticPage** принимает url страницы, путь, по которому сохранится страница, метод записи и заголовки запроса. Метод записи «wb» используется для сохранения картинок, по умолчанию writeMethod установлен как «w», что используется для html-страниц. Если заголовки запросов не указаны, то будут использоваться заголовки со случайным user-agent. Метод возвращает статус ответа сайта, что должно использоваться для введения проверок + +2. Метод **getDynamicPage** с помощью библиотеки Selenium получает динамически обновляемую страницу. Это помогает, когда контент на странице подгружается динамически. Принимает url страницы, путь сохранения, closeWindow и timeSleep. По умолчанию браузер Selenium открывается в фоновом режиме, и работу браузера не видно, но если closeWindow указать как False, то будет виден процесс выполнения кода. С помощью timeSleep можно увеличить время загрузки страницы если контент на ней долго подгружается + +3. Метод **gpsa** (get page semi-automatically) похож на метод getDynamicPage, но работает в полуавтоматическом режиме. Он открывает страницу сайта и ждёт пока не будет нажат Enter в терминале. В этот момент можно зарегистрироваться на сайте и/или перейти на нужную вкладку сайта, после чего нажать Enter и метод спарсит страницу. Подходит для лент соцсетей, где неавторизованным пользователям контент ограничен. Принисает такие же аргументы для таких же целей, что и getDynamicPage, за исключением closeWindow + +4. Метод **returnBs4Object** возвращает объект beautifulsoup4. Принимает путь до html-страницы, содержимое которой преобразует в объект beautifulsoup, кодировку открытия файла (по умолчанию UTF-8) и тип парсера (по умолчанию lxml). + +5. Метод **getAttributes** нужена чтобы получить список атрибутов из списка объектов bs4. Принимает список объектов bs4 и название атрибута который будет извлекаться из элементов списка + +6. Метод **getTexts** нужена чтобы получить список текста из списка объектов bs4. Принимает список объектов bs4 и параметр needFix. Если этот параметр установлен как True, то из текста будут удалены \n, \t и пробелы с концов + +7. Метод **pprint** используется для вывода значений переменных у которых большая вложеность. Например, если у Вас есть массив объектов, где в качестве значения ключа используется другой массив объектов + +8. Метод **mkdir** используется для создания папки с именем _nameDir_ если она ещё не существует + +### Пример парсера с использованием ipars: + +```py +# О классе ProgressBarManager читай ниже +from ipars import Pars, ProgressBarManager +p = Pars() +nameFile = 'index.html' + +# Получаем html страницу +p.getDinamicPage(nameFile, 'https://duckduckgo.com/?q=теплица+социальных+технологий+youtube&iar=videos&atb=v454-1', closeWindow=0) + +# Получаем объект BautifullSoup +soup = p.returnBs4Object(nameFile) + +# Находим все карточки ответов +# Первые результаты выдачи те что хотелось получить, а остальные нет. Поэтому нам желательно получить первые 84 элемента +allCards = soup.find_all(class_='b_NgmZrVnRtV8MZMEjLs')[:84] + +# Получаем все изображения +allImg = [card.find('img') for card in allCards] + +# Получаем все ссылки +allSrc = p.getAttributes(allImg, 'src') + +# Создаём папку img если её ещё нет +nameFolder = 'img' +p.mkdir(nameFolder) + +# Создаём объект ProgressBarManager +bar = ProgressBarManager(len(allSrc)) + +# Скачиваем картинки +for index, url in enumerate(allSrc): + url = 'https:' + url + p.getStaticPage(f'./{nameFolder}/img{index}.png', url, writeMethod='wb') + bar.next() +bar.finish() +``` + +### Пример использования методов _getAttributes_ и _getTexts_ + +```py +from ipars import Pars +p = Pars() + +p.getStaticPage('./index.html', 'https://google.com') +soup = p.returnBs4Object('./index.html') + +allTegA = soup.find_all('a') +a1 = p.getTexts(allTegA, needFix=1) +p.pprint(a1) + +a2 = p.getAttributes(allTegA, 'href') +p.pprint(a2) +``` diff --git a/pages/ru/ProgressBarManager_RU.md b/pages/ru/ProgressBarManager_RU.md new file mode 100644 index 0000000..34a0283 --- /dev/null +++ b/pages/ru/ProgressBarManager_RU.md @@ -0,0 +1,64 @@ +### Работа с ProgressBarManager + +Класс создаёт прогресс-бар для лучшей видимости выполнения кода. Принимает пять аргументов: + +1. **max**: обязательный параметр, который указывает максимальное значение итераций в прогресс-баре + +2. **message**: сообщение перед прогресс-баром + +3. **color**: цвет прогресс-бара + +4. **fill**: заполнитель для сделанной части + +5. **width**: размер прогресс-бара в символах + +```py +from ipars import ProgressBarManager + +bar = ProgressBarManager(100) # Здесь max установлен как 100 +``` + +### Коротко о методах ProgressBarManager + +1. Метод **next** запускает следущую итерацию прогресс-бара + +2. Метод **finish** завершает работу прогресс-бара + +### Пример использования ProgressBarManager + +```py +# Импортируем библиотеки +from ipars import ProgressBarManager +from time import sleep + +maxValue = 300 +# Создаём прогресс-бар по умолчанию +bar = ProgressBarManager(maxValue) + +# Имитируем работу +for _ in range(maxValue//2): + sleep(0.1) + bar.next() + +# Выключаем прогресс-бар +bar.finish() + + + +# Создаём более кастомизированный прогресс-бар +bar = ProgressBarManager( + maxValue, + message='Процесс скачивания', + color='red', + fill='*', + width=50 +) + +# Имитируем работу +for _ in range(maxValue): + sleep(0.1) + bar.next() + +# Выключаем прогресс-бар +bar.finish() +``` diff --git a/pages/ru/TimerManager_RU.md b/pages/ru/TimerManager_RU.md new file mode 100644 index 0000000..7a3fb86 --- /dev/null +++ b/pages/ru/TimerManager_RU.md @@ -0,0 +1,35 @@ +### Работа с TimerManager + +Класс TimerManager предназначен для отслеживания времени выполнения кода. Он позволяет получить общее время работы в различных форматах. + +```py +from ipars import TimerManager + +t = TimerManager() +``` + +### Коротко о методах TimerManager + +1. Метод **start** — точка начала отсчёта времени + +2. Метод **end** — конечная точка отсчёта времени + +3. Метод **getWorkTime** возвращает общее время работы в указанном формате. Поддерживаемые форматы: _seconds_, _minutes_, _hours_. Параметр _ndigits_ указывает количество знаков после запятой для округления, по умолчанию число не округляется. + +### Пример использования TimerManager + +```py +from time import sleep +from ipars import TimerManager +t = TimerManager() + +# Засекаем время +t.start() +sleep(2) # имитация двухсекундной работы +t.end() + +# Выводим результат в разных форматах +print(f"Время работы в секундах: {t.getWorkTime()}") # 2.0008320808410645 +print(f"Время работы в минутах: {t.getWorkTime(ndigits=2, format='minutes')}") # 0.03 +print(f"Время работы в часах: {t.getWorkTime(ndigits=4, format='hours')}") # 0.0006 +``` diff --git a/pages/ru/ZipManager_RU.md b/pages/ru/ZipManager_RU.md new file mode 100644 index 0000000..8efb5d6 --- /dev/null +++ b/pages/ru/ZipManager_RU.md @@ -0,0 +1,33 @@ +### Работа с ZipManager + +Класс ZipManager нужен для архивации папоки файлов. Он принимает принимает только один аргумент — уровень сжатия файлов. + +'none' => Без сжатия + +'normal' => Обычное сжатие + +'hard' => Увеличенное сжатие + +'maximum' => Максимальное сжатие + +```py +from ipars import ZipManager + +z = ZipManager() +``` + +### Коротко о методах ZipManager + +1. Метод **zip_file** используется для архивирования одного файла. Принимает путь до исходного файла и путь выходного файла + +2. Метод **zip_folder** используется для архивирования каталога. Принимает путь до исходного каталога и путь выходного файла + +### Пример использования ZipManager + +```py +from ipars import ZipManager +z = ZipManager(compression='maximum') + +z.zip_file('./your_file.txt', 'file_archive_maximum.zip') +z.zip_folder('./your_folder/', 'folder_archive_maximum.zip') +``` diff --git a/pinguin_png.png b/pinguin_png.png new file mode 100644 index 0000000..0b9b87c Binary files /dev/null and b/pinguin_png.png differ diff --git a/styles.css b/styles.css new file mode 100644 index 0000000..1630b07 --- /dev/null +++ b/styles.css @@ -0,0 +1,11 @@ +#docsify-darklight-theme { + right: 5px; +} + +a:visited { + color: inherit; /* Убирает изменение цвета для посещенной ссылки */ +} + +.clear-button.show svg{ + margin-top: 8px; +}