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

TGINSIGHT SIMILAR POSTS

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

Изворен канал @pythonotes · Post #121 · 20 јул.

Регулярно требуется преобразовать какой-либо текст в максимально совместимый текст для URL, имени файла, имени объекта в каком-то софте и тд. Требования совместимости простые: в тексте должны быть только допустимые символы. Обычно это a-z, 0-9 и "_" или "-". То есть, только прописные буквы латинского алфавита и цифры (как пример). Допустим, нам нужно название статьи в блоге преобразовать в slug для добавления его в URL этой статьи. Как это лучше всего сделать? В Django по умолчанию есть готовая функция slugify для таких случаев. Но я её никогда не использую. Почему? Потому что её недостаточно! Приведём пример >>> from django.utils.text import slugify >>> slugify('This is a Title') 'this-is-a-title' Пока всё отлично >>> slugify('This is a "Title!"') 'this-is-a-title' Спец символы удалились, всё хорошо. >>> slugify('Это заголовок статьи') '' Вот и приехали 😢. Если текст не английский то буквы просто игнорируются. Можно это поправить >>> slugify('Это заголовок статьи', allow_unicode=True) 'это-заголовок-статьи' Но тогда мы не вписываемся в условие. У нас появилась кириллица в тексте. Так как я часто пишу сайты для русскоязычных пользователей эта проблема весьма актуальна. Я не использую стандартную функцию и всегда пишу свою. Оригинал я не беру в расчёт и пишу полностью свою функцию. И так, по порядку: 🔸1. Исходный текст: >>> text = 'Мой заголовок №10 😁!' Взял специально посложней со специальными символами. 🔸2. Транслит Необходимо сделать транслит всех символов в латиницу. Здесь очень выручает библиотека unidecode. Помимо простого транслита кириллицы в латиницу она умеет преобразовывать спец символы и иероглифы в текстовые аналоги. from unidecode import unidecode >>> unidecode("Ñ Σ ® µ ¶ ¼ 月 山") 'N S (r) u P 1/4 Yue Shan' Очень крутая библиотека, советую👍 В нашем случае получаем такое преобразование: >>> text = unidecode(text) >>> print(text) 'Moi zagolovok No. 10 !' Отличный транслит. Смайл просто удалился, хотя я ждал что-то вроде :). Ну и ладно, всë равно невалидные символы. А еще наш код уже поддерживает любой язык, будь то хинди или корейский. 🔸4. Фильтр символов Unidecode не занимается фильтрацией по недопустимым символам. Это мы делаем в следующем шаге через regex. Просто заменим все символы на "_" если они вне указанного диапазона. >>> text = re.sub(r'[^a-zA-Z0-9]+', '_', text) >>> print(text) 'Moi_zagolovok_No_10_' Символ "+" в паттерне выручает когда несколько недопустимых символов идут рядом. Все они заменяются на один символ "_". 🔸5. Slugify Осталось удалить лишние символы по краям и сделать нижний регистр >>> text = text.strip('_').lower() >>> print(text) 'moi_zagolovok_no_10' Получаем отличный slug! 😎 🌎 Полный код в виде функции. ______________ PS. Проверку что в строке остался хоть один допустимый символ я бы вынес в отдельную функцию. #libs#tricks#django

Резултати

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

Пребарај: #russiaindia

当前筛选 #russiaindia清除筛选
Russian MFA 🇷🇺

@MFARUSSIA · Post #28744 · 17.03.2026 г., 16:59

🇷🇺🇮🇳On March 17, Russia's Deputy Foreign Minister Alexander Alimov held consultations in New Delhi with India’s Deputy Minister of External Affairs Sibi George on strengthening bilateral coordination at the UN. The Sides exchanged views on key issues on the UN Security Council agenda, including Ukraine, Iran, Venezuela, Gaza, Afghanistan and Myanmar. UN peacekeeping was also discussed. Particular attention was paid to the election of the UN Secretary-General and the Security Council's reform aimed at making it more representative and democratic. The Parties underscored the strong and effective coordination within the UN. Moscow and New Delhi confirmed a high degree of alignment on most global issues and reiterated their shared principled stance in favour of resolving crises on the basis of international law. Both Sides expressed readiness to further enhance cooperation at the UN in line with the specially privileged strategic partnership between Russia and India. 📷© India's Ministry of External affairs #RussiaIndia

Hashtags

🇷🇺🇮🇳📞 Russia's President Vladimir Putin and Prime Minister of the Republic of India Narendra Modispoke over the phone. The President of Russia warmheartedly congratulated Narendra Modi on the success of the Indian People's Party in the general parliamentary elections that finished a few days ago. This reflects the support of the political course pursued by the Indian leadership, recognition of the results achieved in the country's socioeconomic development, and its strengthening international authority. Sides expressed their satisfaction with the current level of especially privileged strategic partnership between Russia and India, which will continue to expand in all areas. It was agreed to continue constructive personal interaction between the two countries' leaders. 📃 A message of congratulations was also sent to Narendra Modi: "The results of the voting once again reaffirm your high personal political reputation, as well as the support of the course you pursue towards India’s fast socioeconomic development and protection of its interests on the global stage. We consider relations of especially privileged strategic partnership with New Delhi of great importance. I am confident that further promotion of mutually beneficial cooperation and giving it new substance aligns with the interests of the Russian and Indian nations. Of course, I also hope that we will continue our open dialogue and constructive joint work on the topical issues on bilateral and international agenda." #RussiaIndia

Hashtags

🇷🇺🚀 🇮🇳 On April 3, the Russian House in New Delhi hosted a photo exhibition from the TASS News Agency’s archive to mark the 40th anniversary of spaceflight of the first Indian cosmonaut Rakesh Sharma as part of the Soviet crew. The event was attended by representatives of the expert community and diplomatic corps, media, employees of the Indian Space Research Organization, students and compatriots. 💬 The exhibition was inaugurated by Roman Babushkin, Minister Counsellor & DCM, Russian Embassy in India, Evgeny Pakhomov, Chief of the Indian Bureau, TASS News Agency, and Sanjeev Kumar Varshney, Adviser & Head, International Cooperation (Bilateral) Division, Department of Science & Technology, Ministry of Science & Technology, Government of India. The audience was also addressed by Wing Commander Rakesh Sharma himself through a video message. He shared his impressions of preparations for the flight, noted the significance of this event as well as expressed confidence in the further successful development of bilateral cooperation in the space sector. 🎬 A documentary titled “How I Became a Cosmonaut” was also shown as part of the event. 📸 The exposition that contains 40 unique archival photographic materials will last until April 16, 2024. 🔸@RusEmbIndia #RussiaIndia

Hashtags

Embassy of Russia in Singapore

@rusembsg · Post #3219 · 25.06.2024 г., 15:15

🇷🇺 🇮🇳 On June 24, in Tehran, on the sidelines of the 19th Asia Cooperation Dialogue Ministerial Meeting, Russian Deputy Foreign Minister Andrey Rudenko had a meeting with Dammu Ravi, Secretary (ER), Ministry of External Affairs, Government of India. 💬 The parties exchanged views on topical issues of the Russian-Indian cooperation, including in the economic and transport spheres. Particular attention was paid to the interaction within BRICS and the SCO. 🤝 They reaffirmed the commitment to further intensify bilateral political dialogue. 🔸@RusEmbIndia #RussiaIndia

Hashtags

Embassy of Russia in Singapore

@rusembsg · Post #3090 · 06.06.2024 г., 02:25

🇷🇺🇮🇳📞 Russia's President Vladimir Putin and Prime Minister of the Republic of India Narendra Modispoke over the phone. The President of Russia warmheartedly congratulated Narendra Modi on the success of the Indian People's Party in the general parliamentary elections that finished a few days ago. This reflects the support of the political course pursued by the Indian leadership, recognition of the results achieved in the country's socioeconomic development, and its strengthening international authority. Sides expressed their satisfaction with the current level of especially privileged strategic partnership between Russia and India, which will continue to expand in all areas. It was agreed to continue constructive personal interaction between the two countries' leaders. 📃 A message of congratulations was also sent to Narendra Modi: "The results of the voting once again reaffirm your high personal political reputation, as well as the support of the course you pursue towards India’s fast socioeconomic development and protection of its interests on the global stage. We consider relations of especially privileged strategic partnership with New Delhi of great importance. I am confident that further promotion of mutually beneficial cooperation and giving it new substance aligns with the interests of the Russian and Indian nations. Of course, I also hope that we will continue our open dialogue and constructive joint work on the topical issues on bilateral and international agenda." #RussiaIndia

Hashtags

Russian Mission to ASEAN

@aseanrussia · Post #636 · 06.09.2023 г., 10:47

🇷🇺🇮🇳 Russia’s Foreign Minister Sergey Lavrov and Minister of External Affairs of India Dr. Subrahmanyam Jaishankar hold talks on the margins of the 18th East Asia Summit. 📍Jakarta, September 6 #RussiaIndia

Hashtags

Russian Mission to ASEAN

@aseanrussia · Post #288 · 02.03.2023 г., 02:03

🇷🇺🇮🇳 Foreign Minister Sergey Lavrov holds a meeting with Minister of External Affairs of the Republic of India Dr Subrahmanyam Jaishankar. 📍 New Delhi, March 1 #RussiaIndia

Hashtags

Russian Mission to ASEAN

@aseanrussia · Post #1127 · 03.07.2024 г., 07:08

🇷🇺🇮🇳 Russia’s Foreign Minister Sergey Lavrov and Foreign Minister of India Dr. Subrahmanyam Jaishankar hold talks on the sidelines of the Shanghai Cooperation Organisation (#SCO) Heads of State Council meeting. 📍 Astana, July 3 #RussiaIndia

Russian MFA 🇷🇺

@MFARUSSIA · Post #29195 · 13.04.2026 г., 10:31

Embassy of Russia in India: 🇷🇺🇮🇳April 13 marks the 79th anniversary of diplomatic relations between Russia and India. The status of a Special and Privileged Strategic Partnership reflects the scale and depth of Russia-India ties across the political, trade, economic, scientific, technological, educational and cultural spheres. Flagship areas of bilateral cooperation include joint investment projects, the development of transport corridors, as well as collaboration in space exploration and nuclear energy. Among our foremost priorities are energy security and defence cooperation. The dynamic growth of bilateral engagement at all levels, including business and interregional contacts, as well as record trade turnover, reflects our shared commitment to the steady further development of equal, trusting and mutually beneficial cooperation. Tourist flows are growing, while humanitarian exchanges continue to expand. 🤝Russia and India are bound by decades of fruitful and effective interstate cooperation, as well as by centuries of genuine friendship and civilisational dialogue. ☝️Our common task is to preserve and build upon this unique legacy. #RussiaIndia#DruzhbaDosti

ПретходнаСтраница 1 од 5Следна