Функция 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
The death sentence of the leader of the Egyptian Muslim Brotherhood was issued
A court in #Egypt has issued a death sentence for Muslim Brotherhood leader Mohammad Badie and three of its senior members.
In 2012, the Egyptian people succeeded in overthrowing the dictatorial government of Egypt by giving thousands of martyrs. But after coming to power, Muhammad Morsi, like Hosni Mubarak, started his relations with America and Israel. A year later, the Egyptian people's revolution was overthrown by an Israeli coup and the Sunni Muslim Brotherhood was massacred.
Perhaps Arabs and Turks will understand hundreds of years later that the cost of resistance against the West is lower than compromise.
https://t.me/YediotNewsChat
#Egypt, Temples of Abu Simbel 🇪🇬
The temples of Abu Simbel are the most famous in all Egypt after the Pyramids of the Giza dedicated to Ramses II and his wife.
⭐️ One of the most beautiful spots in Sharm El Sheikh – Farsha Cafe
📏
📏
📏
📏
📏
📏
📏
📏
✅Here, you fully experience the Egyptian vibe and immerse yourself in the atmosphere of an Eastern fairy tale.
📏
📏
📏
📏
📏
📏
📏
📏
#Egypt🇪🇬@voyage
🗺Egypt 🇪🇬
The "City of the Dead" in the Minya Province is a necropolis over 2,500 years old.
Archaeologists have discovered tombs in this area belonging to the priests of Thoth, the ancient god of the moon and wisdom.
Minya Province is also home to the ancient cemetery of Zawiyet el-Mayyitin ("Edge of the Dead"), the world's largest burial site where the deceased were laid to rest since the time of the ancient Egyptian pharaohs.
#Egypt
@voyage
📍 Egypt, Sharm El-Sheikh, Al-Sahaba Mosque 🇪🇬
The second largest mosque in Sharm El-Sheikh, but undoubtedly the most beautiful. Additionally, it is one of the newest mosques in Egypt—opened in March 2017, it was constructed between 2011 and 2017.
The mosque was designed by Egyptian architect Fouad Tawfik Hafez—free of charge. 🕌
Built on a 3,000 square meter area with two minarets reaching 81 meters high, the mosque's roof rises to 36 meters. It can accommodate about 3,000 visitors. 🙌🏗
The most fascinating aspect is its unique architectural style, fundamentally Ottoman but with vivid Fatimid elegance, modern features, and Maghrebi touches. It's a sight worth seeing.
#Egypt
@voyage
📍 Egypt, Tomb of Ramses VI in Luxor 🇪🇬
The tomb of Pharaoh Ramses VI was created in the 12th century BCE. It is one of the most well-preserved tombs in the Theban necropolis, famous for its illustrations to the "Book of Caves," which tells about the most secret areas of the other world, as well as astronomical images. ⚰️
The ceiling of the burial chamber is covered with two huge figures of Nut – the goddess of our sky, and Naunet – the goddess of the sky of the other world.
The passage leading to the burial chamber of the Egyptian king Ramses VI is carved at a depth of more than 90 meters in the mountain rock. ⛰
#Egypt
@voyage
Russian ‘Baby Yoga’ 👶🏻
#video#Egypt
Russian PE instructor Lena Fokina has come up with an unorthodox way of making babies strong and resilient, but her method makes a lot of people cringe. Elena grasps the little tykes by their wrists and feet and spins and flips them over and around her head like they were rag dolls.
Lena teaches her bizarre ‘baby yoga’ to parents who want to discover their babies’ natural abilities, but some critics say her innovation is actually baby abuse. Videos of the PE teacher spinning newborns and dipping their heads in the sea have been removed from social media and petitions have appeared on the web calling for Lena’s methods to be banned.
What do you think? Is it baby yoga or baby abuse?
Follow: https://t.me/rtdocumentary
Egypt’s Garbage City
#video#Egypt
Meet the Zabbaleen, Cairo’s traditional garbage collectors. Generations of Zabbaleen have been recycling Cairo’s trash for more than half a century. They are so good at it that they recycle up to 85% of the capital’s waste. To give you some perspective, a whopping 20 million people live in the Greater Cairo area. Imagine how much waste they produce every day!
Zabbaleen’s garbage industry is an organized network of tens of thousands of people, each playing their own part. They gather, transport, and sort the rubbish. Even pigs play an important role, as they are fed the organic food waste.
The Zabbaleen garbage collectors are largely independent from the rest of Cairo and live by their own rules. For example, the Zabbaleen never collect waste from a colleague’s turf. They have their unofficial mayor, shops, cafes, shishas, and schools.
Follow: https://t.me/rtdocumentary