Функция sub в regex может принимать функцию в качестве аргумента repl.
📄 Из документации:
If repl is a function, it is called for every non-overlapping occurrence of pattern. The function takes a single match object argument, and returns the replacement string.
То есть для каждого совпадения будет вызвана функция для вычисления замены вместо замены на одну и ту же строку для всех совпадений.
Иными словами, для замены разных совпадений на разные строки не потребуется запускать re.sub() много раз для каждой строки замены. Достаточно определить функцию, которая вернёт строку для каждого из совпадений.
Описание слишком запутанное🤔, давайте лучше рассмотрим на простом примере:
Создаем карту замены. То есть какие строки на какие требуется менять.
remap = {
'раз': '1',
'два': '2',
'три': '3',
'четыре': '4',
'пять': '5',
}
Пишем функцию поиска строки для замены. Единственным аргументом будет объект re.Match.
Используя данные этого объекта мы вычисляем замену on-the-fly!
def get_str(match: re.Match):
word = match.group(1)
return remap.get(word.lower()) or word
Пример текста.
text = '''Раз Два Три Четыре Пять
Вместе будем мы считать
Пять Четыре Три Два Раз
Мы считать научим вас
'''
Теперь запускаем re.sub и вместо строки замены (repl) подаём имя функции.
(Данный паттерн ищет отдельные слова в тексте)
>>> print(re.sub(r'(\w+)', get_str, text))
1 2 3 4 5
Вместе будем мы считать
5 4 3 2 1
Мы считать научим вас
Думаю, достаточно наглядно 🤓
#libs#regex
#JavaScript#Beginners
🧰
JavaScript for Beginners
The JavaScript for Beginners course aims to teach students who are new to JavaScript the fundamentals of the programming language. The course is taught by Darragh O’Neill a Udemy Instructor who has has received excellent reviews on the platform and has at present a 4.7 star rating.
The course also contains several mini-projects and challenges so we can apply the JavaScript syntax that we have learnt. The course has overs 13+ hours of content and by the end of this course students will be familiar with all the fundamental aspects of the JavaScript language including data types, variables, let, const var, arrays, objects, functions, manipulating the DOM and more.
🔗Link
-----
Canal principal:@repo_science
Cupones: @freecoupons_reposcience
-----
#Python#Excel#beginners
💻
Python in Excel
🗣 Scott Simpson
⏰30m
Get a high-level overview of the Python in Excel features launched in the public beta preview.
-----
Main channel: @repo_science
Coupons: @freecoupons_reposcience
-----
😁Blue Print To Beginner: Intermediate Leglocks By Tom DeBlass😁
➡️Attack The Lower Body With Highly Effective Submission Locks, Taught By One Of Grappling’s Most In-Demand Instructors - Tom DeBlass
➡️Tom DeBlass is a Renzo Gracie black belt who has spent years training with, learning from, and training some of the best grapplers and instructors in all of Brazilian jiu-jitsu - including Gordon Ryan, Garry Tonon, and more
➡️Set up your attacks from common grappling positions like the butterfly guard, closed guard, half guard, and more as Tom shares how to learn faster and cut through the mistakes easier
$127😍$11.99😍
❗️Channel Info and FAQ (MUST CHECK BEFORE BUY)❗️
📱Payment: 📱📱📱
💰Submeta FOR FREE
🌈UFC Picks
👑MasterClass
✈️@bjjfanaticsinstructionals
#TomDeblass#Leglocks#Beginners#NoGi
💁♀️Buy
💁♀️
#ruby#beginners#hacktoberfest#hacktoberfest2020#helm#kubernetes#kubetools
Kubernetes is a powerful tool for managing containerized applications. To learn Kubernetes, you can use platforms like Kubelabs, which offer interactive tutorials and labs. These resources help you understand Kubernetes concepts from the basics to advanced levels. By using these platforms, you can practice deploying applications, managing resources, and ensuring high availability and scalability. This hands-on approach helps you gain practical experience and improve your skills in managing complex applications efficiently.
https://github.com/collabnix/kubelabs
#webScraping#Python#Scrapy
🐍
Scrapy course - Python web scraping for beginners
The Scrapy #Beginners Course will teach you everything you need to learn to start scraping websites at scale using #Python Scrapy.
Topics
- Creating your first #Scrapy spider
- #Crawling through websites & scraping data from each page
- Cleaning data with Items & Item Pipelines
- Saving data to CSV files, #MySQL & #Postgres#databases
- Using fake #user-agents & headers to avoid getting blocked
- Using #proxies to scale up your web scraping without getting banned
- Deploying your #scraper to the cloud & scheduling it to run periodically
🗣️ Joe Kearney.
🔗Link
📢#youtube
⭐️ Resources ⭐️
Course Resources
- Scrapy Docs
- Course Guide
- Course Github
- The Python Scrapy Playbook
-----
Main channel: @repo_science
Coupons: @freecoupons_reposcience
-----