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

Резултати

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

Пребарај: #rgo

当前筛选 #rgo清除筛选

Национальная премия «Хрустальный компас» — одна из самых престижных наград в области географии, экологии и смежных наук! 🏆 В 2026 году уникальные хрустальные статуэтки будут вручены уже в 14-й раз. Лауреатами станут авторы выдающихся исследований и проектов, а также организации и инициативные группы, внесшие значимый вклад в сохранение природы, культурного и исторического наследия. 👩‍🎓 К участию приглашаются: — научные и образовательные учреждения — творческие союзы и организации — общественные деятели и инициативные группы — компании и частные лица из России и других стран. 📋 Приём заявок открыт до 10 февраля 2026 года. Не упустите шанс стать частью международного сообщества, объединяющего исследователей, путешественников и защитников природы более чем из 50 стран мира! 🔗 Подробная информация и подача заявок: https://clck.ru/3PEnsz #ХрустальныйКомпас#RGO#Наука#Экология#Geography#CrystalCompass#Наследие#Премия

خانه روسی در تهران

@Rossotrudnichestvo_in_Iran · Post #802 · 05.09.2024 г., 10:42

🇷🇺🌊🌊🌊 🇮🇳 On September 2, Ratish Nair, Honorary Consul of Russia in Trivandrum (Karnataka, India), began a journey along the route of Afanasy Nikitin. The ambitious project is dedicated to the 555th anniversary of the famous "Journey Beyond Three Seas". 📍 The starting point of the journey was the embankment named after the famous Russian traveler Afansy Nikitin in Tver. ⚡️ Ratish Nair met Senator of the Federation Council of Russia from the Tver Region Lyudmila Skakovskaya and Rector of Tver State University Sergei Smirnov. I am sure that this is a wonderful undertaking - repeating the route of the Tver merchant Afanasy Nikitin. This will help educational and outreach work, draw attention to the traveler's personality, and strengthen ties between our countries. I am sure that in our country, preserving and studying history is one of the most important areas of work, the Senator emphasized. Even in India, not everyone knows that Afanasy Nikitin is the first foreigner who came to our country for peaceful purposes. Friendly relations between India and Russia should be strengthened. This is the main goal of my trip. I am sure that the trip, repeating the path of the Russian traveler, will help to show Russia as it is and open it to foreigners without speculation and fakes, said Ratish Nair. 🗣The meeting participants discussed the opening of Russian online educational courses in Russian in the Indian state of Karnataka, as well as other educational initiatives. 🗺 The head of the Russian House in Trivandrum will visit four more countries after Russia. His route, like 555 years ago, will lie from Tver to Astrakhan along the Volga river, then by car to Derbent, from there to 🇦🇿Azerbaijan, then to 🇮🇷 Iran, from there by plane to 🇴🇲 Oman, and then to 🇮🇳 India. This project is organized by #Rossotrudnichestvo, the Russian Ministry of Foreign Affairs (#MFA), the #RusskiyMirFoundation, and the Russian Geographical Society (#RGS, #RGO), with #Rosatom and #Sber as partners. #RussianHouse#RussianHouseTrivandrum#JourneyBeyondThreeSeas #Voyage555