Функция 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
News: #Amnesty flags impunity, forced eviction, and shrinking civic space in #Ethiopia’s 2025 human rights record
Amnesty International has raised alarm over ongoing human rights violations in Ethiopia, citing entrenched impunity, continued armed conflict, and a tightening grip on civic space throughout 2025.
“Impunity for past and ongoing violations persisted,” Amnesty said, pointing to systemic failures to investigate and prosecute abuses.
https://addisstandard.com/?p=56612
📰 NEWS | Venezuela: Rodríguez Hosts US Chargé d’Affaires Dogu in Presidential Palace
Venezuelan Acting President Delcy Rodríguez hosted US Chargé d'Affaires Laura Dogu in Miraflores Palace on Monday.
The meeting capped a lightning-fast diplomatic rapprochement following the January 3 US strikes and kidnapping of President Nicolás Maduro.
Days earlier, Rodríguez announced plans for an "amnesty law" to promote peace and coexistence in the country.
Follow the link to read the report: https://venezuelanalysis.com/news/venezuela-rodriguez-hosts-us-charge-daffaires-dogu-in-presidential-palace/
#Diplomacy#Amnesty#DelcyRodríguez#Imperialism
#Ethiopia: OLA outlines factual error in #Amnesty report; calls for independent investigation
The Oromo Liberation Army (#OLA) has rejected findings of a recent report by Amnesty International accusing its fighters of gang rape and sexual slavery against women in #western_Oromia, alleging that the report contains “serious methodological flaws and factual errors,” and calling for an independent investigation into abuses committed in the region.
In a press release issued on 06 March, the OLA said that while it condemns all forms of gender-based violence and supports efforts to document abuses against civilians, Amnesty’s report titled “No One Came to My Rescue” suffers from investigative shortcomings & fails to conclusively identify the perpetrators of the crimes described.
The armed group argued that Amnesty itself acknowledged in the report that it could not verify the identities of the alleged perpetrators at the time of publication, a point the OLA said..
Read more: https://addisstandard.com/?p=55634
Dear Members,
You would observe that NIDO Russia has not taken part in disseminating any news on amnesty. Observant people have called privately to inquire and we have guided them as usual. Some have taken matters into their hands and are suffering the consequences, not one, not two. Please before you rush, it may be useful to contact executives in the organisations that you belong. Don't fall prey to ambiguity.
A word is enough for the wise.
Have a beautiful day ahead!
Dr. Godwin Ibe
https://t.me/nido_russia/1936
#migration#nidorussia#amnesty#Nigeria#russia
#Ethiopia: OLA fighters accused of gang rape, sexual slavery against women in #Oromia, Amnesty report
#Amnesty International has accused fighters of the Oromo Liberation Army (#OLA) of committing gang rape, sexual slavery, and other abuses against women and girls during the ongoing armed conflict in Ethiopia’s Oromia region, warning that the violations have contributed to mass displacement and long-term trauma for survivors.
In a new briefing titled “No One Came to My Rescue: Gang Rape, Sexual Slavery, and Mass Displacement of Women in Oromia, Ethiopia,” the rights group said it documented 10 cases of sexual violence in the #Sayo and #Anfillo districts of #Kellem_Wallaga zone, areas it described as strongholds of the OLA.
Amnesty said that the conflict between the OLA and Ethiopian government forces — including the #ENDF, Oromia #Special_Police, Oromia regional police, and local militias — meets the threshold of a non-international armed conflict under .....
Read more: https://addisstandard.com/?p=55611