Функция 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
🇭🇳🇮🇱Israel, la prioridad del nuevo Gobierno hondureño
La Biblia ceremonial de juramento aún no se había enfriado y ya el presidente hondureño Nasry Asfura estaba saludando efusivamente a Nadav Goren, embajador de Israel en la nación centroamericana.
Tanto así, que el Ministerio de Relaciones Exteriores de Israel no pudo ocultar su emoción: "Minutos después de prestar juramento, Nasry Asfura eligió su primer acto: aceptar las credenciales del embajador de Israel, señalando un fuerte compromiso con las relaciones entre Israel y Honduras".
Asfura, de 67 años, obtuvo el respaldo de Trump, Milei y la notoria banda de narcotraficantes MS-13, que "hizo campaña" en su nombre con una amplia acción de intimidación a los votantes en el período previo a la votación del 30 de noviembre.
Trump amenazó abiertamente con cortar la ayuda estadounidense a Honduras si Asfura no era elegido… Ahora sabemos por qué.
#honduras
———
Únete a la lucha por la verdad en
📱Telegram
🫥Odysee
📱X (Twitter)
#video#Honduras
Honduras is one of the most dangerous places to be a woman. The country has the highest rate of femicide, gender-based murder, in Latin America. Women are easy targets for gangs that wage war against each other on the streets of Honduras. Stepping outside your home can sometimes be deadly.
These parents lost their daughter, and they have little hope the perpetrators will be held to account. For more, watch the new documentary Honduran Femicide.
It's also available on Odysee odysee.com/@RTDocumentary:4 Watch all of our films there!
Follow: https://t.me/rtdocumentary
#Honduras#administración Huelga de trabajadores del Servicio Autónomo Nacional de Acueductos y Alcantarillados (SANAA). https://www.latribuna.hn/2023/09/26/prosigue-paro-de-labores-en-el-sanaa-por-falta-de-pago/
#Honduras#sanidad Huelga de aseadoras del hospital psiquiátrico Mario Mendoza. https://hch.tv/2023/09/12/les-deben-cuatro-meses-en-paro-por-falta-de-pago-aseadoras-del-psiquiatrico-mario-mendoza/
#photo#Honduras
This woman kills for a living. She’s an assassin in one of the gangs in San Pedro Sula, once known as the most dangerous city in the world with the highest murder rate. RT Documentary’s Natalya Karachkova interviewed her during a trip to Honduras.
She had to kill three people in a week to become a gang member, which she joined when she was only 12. During the interview, she put a gun between her legs to have quick access to it just in case.
Members of the gang like her don’t get paid. Everything she gets has to be brought to the boss, who distributes it among the gang members. If you’d like to learn more about the criminal gangs in Honduras, subscribe to our channel on Telegram and YouTube. You’ll be the first to find out about the film premiere ;)
Follow: https://t.me/rtdocumentary
📄 El comunicado de prensa de la Cancillería de Rusia respecto a los resultados de las elecciones generales en #Honduras
El 30 de noviembre se celebraron las elecciones generales en la República de Honduras.
Tras un prolongado recuento de resultados en la contienda presidencial, el 24 de diciembre el Consejo Nacional Electoral del país anunció oficialmente el ganador del máximo cargo Estatal al líder del Partido Nacional, Nasry Juan Asfura Zablah, quien obtuvo el 40,26% de los votos.
En Moscú provienen del respeto incondicional a la voluntad de los ciudadanos de Honduras, su soberanía nacional e independencia de la República.
🤝 La Parte Rusa confía en que las relaciones tradicionalmente amistosas entre Moscú y Tegucigalpa mantendrán su continuidad y seguirán desarrollándose de manera constructiva en beneficio de nuestros países y pueblos.
🇷🇺🇭🇳#RusiaHonduras
Miguel Díaz-Canel Bermúdez
(@DíazCanelB) en X)
A pocas horas de la Cumbre #CELAC en Tegucigalpa, hemos tenido un encuentro muy emotivo con colaboradores cubanos de salud y educación, y con hondureños que sienten profundo amor por nuestro país. Les aseguramos que #Honduras y su querido pueblo pueden seguir contando con #Cuba.
Miguel Díaz-Canel Bermúdez
(@DíazCanelB) en X)
A pocas horas de la Cumbre #CELAC en Tegucigalpa, hemos tenido un encuentro muy emotivo con colaboradores cubanos de salud y educación, y con hondureños que sienten profundo amor por nuestro país. Les aseguramos que #Honduras y su querido pueblo pueden seguir contando con #Cuba.
https://x.com/i/status/1909828113183224024
#México revive el viejo corredor creado para el galeón de Manila y que perdió su relevancia con el canal de #Panamá.
https://www.bbc.com/mundo/articles/cj5vj0yjqydo
#Honduras intenta impulsar la competencia
https://www.portafolio.co/internacional/el-plan-de-honduras-para-construir-un-tren-interoceanico-para-unir-el-atlantico-con-el-pacifico-590072
#Honduras
L'ex Presidente Juan Orlando #Hernández (#PNH|Destra) è stato estradato negli USA. Il Dipartimento di Giustizia degli Stati Uniti ha accusato Hernández di legami con il traffico di droga e il possesso ingiustificato di armi.
@UltimoraPolitics
🌎 In the skies over Honduras and Nicaragua, the mysterious “Lluvia de Peces,” or "Rain of Fish," has been reported for over a century. After intense storms, locals find live fish on land—scientists suspect waterspouts or flooding lift fish from rivers and drop them during heavy rainfall. This phenomenon usually happens near the town of Yoro, typically once or twice a year. ✨
#weather⚡#phenomenon⚡#rainfish⚡#Honduras
👉subscribe Interesting Planet
👉more Channels