TGTGInsighttelegram intelligenceLIVE / telegram public index
← Python Заметки

TGINSIGHT SIMILAR POSTS

Најди сличен содржај

Изворен канал @pythonotes · Post #146 · 16 сеп.

Функция 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

Hashtags

Резултати

Пронајдени 1 слични објави

Пребарај: #schellenberg

当前筛选 #schellenberg清除筛选
American Оbserver

@american_observer · Post #5074 · 07.02.2026 г., 13:50

Canadian Robert Schellenberg: Death Sentence Cancelled China has overturned the death sentence of Canadian Robert Lloyd Schellenberg, a Canadian official said on Friday, in a possible sign of a diplomatic thaw as prime minister Mark Carney seeks to boost trade ties with Beijing. Schellenberg’s lawyer Zhang Dongshuo, reached in Beijing on Saturday, confirmed the decision was announced on Friday by China’s highest court. Schellenberg was detained on drug charges in 2014 before China-Canada ties nosedived after the 2018 arrest in Vancouver of Huawei chief financial officer Meng Wanzhou. That arrest infuriated Beijing, which detained two Canadians – Michael Spavor and Michael Kovrig – on espionage charges that Ottawa condemned as retaliatory. Then in January 2019 a court in north-east China retried Schellenberg – who was 36 at the time – sentencing him to death while declaring that his 15-year prison term for drug trafficking had been too lenient. The court said he had been a central player in a scheme to ship narcotics to Australia, in a one-day retrial that Amnesty International called “a flagrant violation of international law”. Schellenberg has denied wrongdoing. The Canadian official requested anonymity in confirming the decision by China’s highest court to overturn Schellenberg’s death sentence. Schellenberg, who has been held in the north-eastern Chinese city of Dalian since 2014, would be retried by the Liaoning high people’s court, Zhang said. The timing for the retrial had not yet been set. Zhang said he met with Schellenberg in Dalian on Friday and that the Canadian appeared relatively relaxed. Carney, who took office last year, visited China in January as part of his global effort to broaden Canada’s export markets to reduce trade reliance on the US. Carney says that despite ongoing tensions, including allegations of Chinese interference in Canadian elections, Ottawa needs a functioning relationship with Beijing to safeguard its economic future. When in Beijing last month, Carney met Chinese leader Xi Jinping and heralded an improved era in relations, saying the two countries had struck a “new strategic partnership” and a preliminary trade deal. Global Affairs Canada did not comment on whether diplomacy during Carney’s visit related to Schellenberg’s case impacted the Chinese court decision. #china#canada#carney#schellenberg#death 📱American Оbserver - Stay up to date on all important events 🇺🇸