Функция 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
FJORDS(峡湾) 8K 60FPS
Although a sought-after destination in the summer, the Norwegian fjords lay mostly empty in the winter time. However, this time of year is no less magical. This video aim to show this magic, all in glorious 8K resolutions at 60 fps.
挪威峡湾虽然是夏季的热门目的地,但在冬季时空无一人,在一年中的这个时间的景色同样非常不可思议。此视频旨在以60 fps的出色8K分辨率显示这种魔力。
- 作者: Morten Rustad
- https://youtu.be/0pmvuKzBIqM
频道: @View_4k#8k
Hawaii in 8K ULTRA HD - Paradise of North America (60fps)
This videos you can use for learn Nature, about place, River, Country, City, etc with Ultra-HD resolution.
- 原视频: https://youtu.be/PF1EAtMswPo
- 画质(上面链接): 8K60P
- 作者: 8K World
统计: @View_4k#4k#8k
From Darkness To Light
From Darkness To Light is an 8k Time-Lapse film shot by storm chaser Ty Schmitt. All the clips in the film were captured on the Great Plains during the 2019 spring storm season. Ty traveled over 30,000 miles in 3 months chasing Mother Nature's most intense moments.
All images were shot on a Nikon D850, and edited in LRTimelapse, After Effects, and Premiere Pro.
- 原视频: https://youtu.be/MlIXpZFTBP4
- 画质(上面链接): 8K
- 作者: Ty Schmitt
统计: @View_4k#4k#8k
Hawaii in 8K ULTRA HD - Paradise of North America (60fps)
This videos you can use for learn Nature, about place, River, Country, City, etc with Ultra-HD resolution.
- 原视频: https://youtu.be/PF1EAtMswPo
- 画质(上面链接): 8K60P
- 作者: 8K World
统计: @View_4k#4k#8k
From Darkness To Light
From Darkness To Light is an 8k Time-Lapse film shot by storm chaser Ty Schmitt. All the clips in the film were captured on the Great Plains during the 2019 spring storm season. Ty traveled over 30,000 miles in 3 months chasing Mother Nature's most intense moments.
All images were shot on a Nikon D850, and edited in LRTimelapse, After Effects, and Premiere Pro.
- 原视频: https://youtu.be/MlIXpZFTBP4
- 画质(上面链接): 8K
- 作者: Ty Schmitt
统计: @View_4k#4k#8k
Frankfurt
Frankfurt is a city of great diversity. It is a metropolis of banks and big business shows and shopping on the one side, culture and traditions on the other.
- 原视频: https://youtu.be/UaveL8lp_ws
- 画质(上面链接): 8K
- 作者: Cities in 4K
统计: @View_4k#4k#8k
FJORDS(峡湾) 8K 60FPS
Although a sought-after destination in the summer, the Norwegian fjords lay mostly empty in the winter time. However, this time of year is no less magical. This video aim to show this magic, all in glorious 8K resolutions at 60 fps.
挪威峡湾虽然是夏季的热门目的地,但在冬季时空无一人,在一年中的这个时间的景色同样非常不可思议。此视频旨在以60 fps的出色8K分辨率显示这种魔力。
- 作者: Morten Rustad
- https://youtu.be/0pmvuKzBIqM
频道: @V1_BLOG#8k#view
TelegramUltraPrivateChannel #0042
My old designs in 8 Colors
>> FOR <<
#iPhone14
#iPadAir5
#8K#Desktop
----------------------
Prod. By@Hk3ToN
----------------------