Функция 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
🌎 Scientists researching the mysteries of parallel worlds often reference "brane theory," which suggests our universe could be a 3D surface, or 'brane,' floating in higher-dimensional space. In this model, multiple branes—each a universe with its own laws—could exist, and gravity may leak between them, which physicists are testing with experiments at facilities like CERN. ✨
#physics⚡#universe⚡#dimensions
👉subscribe Interesting Planet
👉more Channels
🌎 The concept of "extra dimensions" in physics comes from string theory, which requires at least 10 dimensions for its mathematical consistency. While these extra dimensions could allow for parallel universes, none have been directly detected. Experiments like those at CERN look for signs such as missing energy that might hint at hidden dimensions. ✨
#physics⚡#stringtheory⚡#dimensions
👉subscribe Interesting Planet
👉more Channels
🌎 The concept of higher dimensions beyond the familiar three of space and one of time appears in advanced physics, especially string theory. String theory mathematically requires up to 10 or 11 dimensions to explain gravity and fundamental particles. These extra dimensions are thought to be compact and hidden, possibly curled up at sizes far smaller than atoms. ✨
#dimensions⚡#stringtheory⚡#physics
👉subscribe Interesting Planet
👉more Channels
🌎 In 2022, a study using gravitational wave detectors like LIGO examined whether ripples from colliding black holes hinted at hidden dimensions. The research found no evidence for extra spatial dimensions, setting new constraints on theories that propose parallel universes. ✨
#physics⚡#blackholes⚡#dimensions
👉subscribe Interesting Planet
👉more Channels
🌎 The "brane multiverse" is a scientific idea suggesting our universe might be a three-dimensional "brane" floating in higher-dimensional space. Some versions of string theory propose multiple branes could exist close together, and rare collisions might even trigger new big bangs. The concept arises from efforts to unify gravity with quantum physics. ✨
#multiverse⚡#dimensions⚡#stringtheory
👉subscribe Interesting Planet
🌎 Physicists are searching for evidence of extra dimensions that could exist alongside our three spatial dimensions and time. Experimental efforts, like those at the Large Hadron Collider, look for signs such as missing energy or unusual particle behavior that might indicate the presence of dimensions beyond the familiar four. So far, no direct evidence has been found for extra dimensions. ✨
#physics⚡#dimensions⚡#experiment
👉subscribe Interesting Planet
👉more Channels
Тема шестого дня — картографирование за пределами 2D.
Эту работу подготовил наш коллега @Oreshulya для личного проекта. На карте изображён подводный рельеф небольшого озера Уайтфиш в Канаде. При создании использовалось ПО QGIS для получения картографических данных и Blender 3D для их визуализации.
Основной задачей было показать батиметрические данные в трёхмерном виде, что проблематично сделать с использованием стандартных средств ГИС. Способом изображения для этого была выбрана послойная окраска. Благодаря тому что каждый слой помимо уникального цвета имеет разную высоту в пространстве, создаётся ощущение объёма и глубины, которое на стандартных двумерных батиметрических картах достигается с помощью способа Танака (освещённых горизонталей).
#30DayMapChallenge#Day6#Dimensions#Cartography#GIS