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

Резултати

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

Пребарај: #mozambique

当前筛选 #mozambique清除筛选
POPULAR FRONT

@popularxfront · Post #4895 · 04.02.2026 г., 17:38

🇲🇿#Mozambique: IS-Mozambique (ISMP, Islamic State in Mozambique) released a video today claiming responsibility for an attack last Sunday targeting Mozambican military bases in the Katuba and Namapo areas of Cabo Delgado in the northern part of the country. As a result of the attacks, it is reported that nine Mozambican soldiers were killed. The militants also posted footage showing weapon caches and equipment they captured from the bases. (via @BrantPhilip_ on X)

Hashtags

Russian MFA 🇷🇺

@MFARUSSIA · Post #28776 · 19.03.2026 г., 12:59

⚡️Russia's EMERCOM: On March 19, a special flight of Russia's EMERCOM delivered humanitarian aid to the Republic of #Mozambique. By decision of Russia's President Vladimir Putin, following instructions from the Government of Russia and on the orders of EMERCOM Head Alexander Kurenkov, around 29 tonnes of humanitarian cargo were transported from Moscow. 🛬 An Il-76 aircraft delivered food, essential supplies, as well as tents and blankets for flood-affected communities in the African republic. #RussiaHelps

ጠቅላይ ሚኒስትር ዐቢይ አሕመድ (ዶ/ር) ለሞዛምቢኩ ፕሬዝደንት ዳንኤል ፍራንሲስኮ ቻፖ ደማቅ አቀባበል አደረጉ ************** ጠቅላይ ሚኒስትር ዐቢይ አሕመድ (ዶ/ር) በኢትዮጵያ ይፋዊ የሥራ ጉብኝት ለማድረግ የመጡትን የሞዛምቢክ ፕሬዝደንት ዳንኤል ፍራንሲስኮ ቻፖን በቦሌ ዓለም አቀፍ አውሮፕላን ማረፊያ በመገኘት በክብር ተቀብለዋል። የፕሬዝደንቱ ጉብኝት በሁለቱ ሀገራት መካከል ያለውን ዲፕሎማሲያዊ እና ኢኮኖሚያዊ ግንኙነት ወደ አዲስ ምዕራፍ ያሸጋግራል ተብሎ ይጠበቃል። ጉብኝቱ የሁለቱን ሀገራት ታሪካዊ ግንኙነት ወደ ላቀ ደረጃ የሚያሸጋግር ሲሆን፣ ኢትዮጵያ ለእውነተኛ አፍሪካዊ አጋርነት ያላትን የማይናወጥ ቁርጠኝነት የሚያረጋግጥ መሆኑን የጠቅላይ ሚኒስትር ጽ/ቤት አስታውቋል። #EBC#Ethiopia#PMOEthiopia#Mozambique#diplomacy

Reuters: World

@reutersworldchannel · Post #149314 · 13.10.2021 г., 16:57

The struggle for water in Mozambique's unstable north Aid agencies warn that a shortage of safe water, poor sanitation and inadequate medical services are a looming threat for the communities in Mozambique's Cabo Delgado province #News#Reuters#Mozambique#RedCross Subscribe: http://smarturl.it/reuterssubscribe Reuters brings you the latest business, finance and breaking news video from around the globe. Our reputation for accuracy and impartiality is unparalleled. Get the latest news on: http://reuters.com/ Follow Reuters on Facebook: https://www.facebook.com/Reuters Follow Reuters on Twitter: https://twitter.com/Reuters Follow Reuters on Instagram: https://www.instagram.com/reuters/?hl=en ➖@reutersworldchannel➖

Russian MFA 🇷🇺

@MFARUSSIA · Post #27890 · 26.12.2025 г., 09:35

#RussiaHelps 💬Maria Zakharova: OnDecember 17 inMaputo (#Mozambique) and December 18 inLusaka (#Zambia), official ceremonies marking the delivery of Russian food assistance were held, attended by the Russian Ambassadors to these countries. 🇲🇿 Mozambique received 70 tonnes of vitamin-fortified sunflower oil for those in need. 🇿🇲 Zambia received a similar shipment of 93 tonnes, as well as 648 tonnes of yellow split peas. These humanitarian deliveries were carried out through the UN World Food Programme, funded by Russia’s voluntary contribution for African countries, which amounts to USD 10 million annually. Humanitarian assistance is an integral part of Russia’s support for its partners on the African continent, primarily aimed at helping the most vulnerable groups. 🇷🇺 Russia will continue to contribute to addressing Africa’s socio-economic challenges, using both bilateral assistance mechanisms and the potential of relevant international organizations. (Excerpt from Russian MFA Spokeswoman Maria Zakharova's weekly briefing on December 26)

AREA

@area_eng · Post #120 · 24.07.2025 г., 20:46

Russia and Mozambique may expand energy cooperation During a visit to Moscow, Mozambique Foreign Minister Maria Manuela dos Santos Lucas said that the country views Russia as a strategic partner in the development of the oil and gas sector. For Mozambique, which has the sixth largest natural gas reserves in Africa (about 100 trillion cubic feet), partnership with Russia is indeed of strategic value. Russian companies offer not only investments, but also unique competencies in the development of offshore fields, construction of gas transportation infrastructure and training of qualified personnel. Today, about 40% of Mozambican students in the Russian Federation are studying in specialties needed in the oil and gas sector. Despite Rosneft's withdrawal from the Mozambique LNG project in 2022, Russian companies remain interested in the region. In particular, Gazprom continues to explore the possibility of working on the Mozambican shelf. According to experts, there are several key vectors of cooperation between the parties. This could be the creation of an LNG cluster using Russian technologies, joint projects for gasification of Mozambique regions, as well as the development of educational programs for training personnel. #AREA#Africa#Russia#RussiaAfrica#energy#Mozambique