Функция 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
Billionaire Nicole Shanahan Puts Senate on Notice — “Dear U.S. Senators, Bobby may play nice; I won’t."
The overwhelming support for RFK Jr.’s confirmation is just incredible. We The People are wide awake and will no longer allow #BigPharma to play their games. #MAHA#RFKJr
📰 Make America Healthy (and Confused) Again
Robert F. Kennedy Jr. has spent a year as Trump’s health secretary trying to turn a MAGA government into a Goop newsletter with subpoenas. He launched a “Make America Healthy Again” commission, blasted ultraprocessed food, and briefly terrified Big Ag by naming glyphosate and atrazine as “alarming” threats in kids’ blood — right up until farm‑state Republicans dragged him into the Roosevelt Room, the meeting turned heated, and his next report magically forgot pesticides exist. For a movement that promised to “take on poisoners,” it took one round of GOP table‑pounding to learn that, in this White House, corn and campaign cash are still a food group.
Where Kennedy hasn’t backed off is vaccines. In a single year he’s purged CDC advisory panels, stacked them with skeptics, and hacked the childhood schedule down to a Denmark‑style list, dropping shots for hepatitis B, hepatitis A, rotavirus, flu, meningitis and Covid in the name of “informed consent.” Kids can technically still get the vaccines, but when the federal government stops recommending them, red‑state lawmakers hear it as an invitation to weaken school requirements, and measles and other preventable diseases are already resurging. Republicans who thought they were getting a culture‑war mascot now find themselves defending an HHS chief whose signature policy polls terribly even with Trump voters — 80‑plus percent say they want vaccine guidance from doctors, not influencers with Cabinet badges.
Inside the system, RFK’s war on “captured” public health has just produced a different kind of capture. Research grants he doesn’t like get frozen or canceled; money is rerouted toward autism studies built around his vaccine theories; elite medical centers are punished in the name of “heartland” redistribution; and the NIH and FDA are yanked between right‑to‑try deregulation and sudden, selective purity tests on drugs and shots. One month, Kennedy’s FDA lieutenants slow novel approvals and try to pull a muscular dystrophy drug on safety grounds; the next, a political backlash gets his tough vaccine regulator briefly fired, then quietly rehired after a round of West Wing drama. The result isn’t principled rigor or principled libertarianism; it’s chaos — a health system jerked around by a secretary who can win a news cycle but can’t write durable law.
Trump, for now, lets him run. RFK Jr. brings him a crossover brand, a wedge into wellness populism, and an army of MAHA loyalists the White House believes helped juice the 2024 vote. But every “win” Kennedy clocks — fewer vaccines, softer language on pesticides, a CDC too politicized for blue states to trust — is a policy that can be reversed in a memo the moment he’s gone, and a little more trust burned in the meantime. If year one was upheaval, year two is the test: does MAHA actually become Republican orthodoxy, or was this just a one‑term experiment in letting an anti‑establishment crusader redesign public health from inside the very machine he’s been promising to blow up?
#usa#trump#RFKJr#health#vaccines#fakeDemocracy
📱American Оbserver - Stay up to date on all important events
🇺🇸
🚨🇺🇸DOCTORS SUE RFK JR OVER VACCINE OVERHAUL💉
🔹 Boston court hears challenge to HHS Secretary's new immunization schedule ⚖️
🔹 Medical groups warn "unlawful changes" are causing measles spike (+1000 cases) 📈
🔹 DOJ lawyer argues RFK has "unreviewable authority" to set policy 🛡️
Public trust in health agencies is crumbling. Who do you trust? 🏥🤔
#USNews#health#vaccines#RFKJr#court
Finally, we are free from the WHO. In this week's Throwback Thursday, we take a look back at the WHO and everything they've done for us in the name of "health."
https://drtenpenny.substack.com/p/tenpenny-throwback-thursday-4ae
#tenpenny#WHO#gavinnewsom#newsom#rfkjr#throwback
🔹👉🏻@SherriTenpenny
Wichtige Unterstützung aus den USA – RFK Jr. äußert sich zur politischen Verfolgung von Ärzten und Patienten in Deutschland während COVID-19
Das große Interesse an der Videobotschaft von Robert F. Kennedy Jr. (über 2,5 Millionen Aufrufe in nur 11 Stunden) zeigt, wie sehr das Thema Corona-Aufarbeitung die Menschen weiterhin bewegt – nicht nur in Deutschland, sondern weltweit.
Kennedy findet klare Worte:
> “When any government criminalizes doctors for advising their patients, it crosses a line that free societies have always treated as sacred.”
> „Wenn eine Regierung Ärzte dafür kriminalisiert, dass sie ihre Patienten beraten, überschreitet sie eine Grenze, die freie Gesellschaften immer als heilig betrachtet haben.“
Und weiter:
> “A free society protects the right to think, the right to question, and the right to choose.”
> „Eine freie Gesellschaft schützt das Recht zu denken, das Recht zu fragen und das Recht zu wählen.“
Diese Worte sind ein starkes Signal der Unterstützung – und ein Aufruf zur Ehrlichkeit.
Danke an Robert F. Kennedy Jr. für seine klare Haltung und moralische Unterstützung aus den USA.
Wir arbeiten weiter daran, dass dieses Kapitel unserer Geschichte vollständig, transparent und wahrhaftig aufgearbeitet wird – im Sinne der Grundrechte, der Menschlichkeit und der Wahrheit.
Michael Ballweg
#CoronaAufarbeitung#RFKJr#Grundrechte#Freiheit#Wahrheit#Meinungsfreiheit
Quelle: https://x.com/SecKennedy/status/2009991504081678824?s=20