@developmentnewsindia · Post #44464 · 05.05.2026 г., 16:01
Indian military likely to operationalise Joint Ops Control Centre in May. #Defence
Hashtags
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
Пребарај: #defence
@developmentnewsindia · Post #44464 · 05.05.2026 г., 16:01
Indian military likely to operationalise Joint Ops Control Centre in May. #Defence
Hashtags
@developmentnewsindia · Post #44446 · 05.05.2026 г., 11:00
BEL secured a ₹1,476 crore Ministry of Defence contract for the Indian Army to supply the Ground Based Mobile Electronic Intelligence System (GBMES). This fully indigenous system, designed by Defence Electronics Research Laboratory (DLRL), Hyderabad, and manufactured by BEL, detects, classifies, and locates radar signals, while intercepting and analysing communication signals. #Defence
Hashtags
@developmentnewsindia · Post #44352 · 03.05.2026 г., 05:44
Indian Army BMP-2 flamethrowers. #Defence
Hashtags
@developmentnewsindia · Post #44351 · 03.05.2026 г., 05:17
India to manufacture ~140 AMCA stealth jets at Puttaparthi; Andhra allots 600 acres to Defence Research and Development Organisation. Project size ~₹1 lakh crore; final assembly/testing hub near Aeronautical Development Agency Bengaluru base. #Defence
Hashtags
@developmentnewsindia · Post #44292 · 01.05.2026 г., 13:16
Pune-based Olee Space has delivered India's first private sector developed Directed Energy Weapon (DEW) or Laser Weapon to Indian Army. #defence
Hashtags
@developmentnewsindia · Post #44278 · 01.05.2026 г., 08:09
BREAKING LR-AShM enters Phase-II trial: India successfully test fires Long Range Anti-Ship hypersonic Missile from a #defence facility off Odisha coast. Indigenously developed by DRDO, the two-stage hypersonic glide weapon can strike moving and static naval vessels at distances up to 1,500 km and boasts high-accuracy terminal manoeuvres. Travelling at a speed of over Mach 5, it can also target warships or land surfaces. The missile will have multiple warhead configurations.
Hashtags
@developmentnewsindia · Post #44267 · 01.05.2026 г., 02:34
Paras Defence & Space Technologies has won a significant Rs 7.72 crore contract from DRDO for developing advanced Ku/C-Band Satellite Communication Phased Array Antennas designed for airborne defence applications. The project has a comprehensive timeline extending until April 29, 2028, reflecting the sophisticated nature of the satellite communication technology development required for modern defence operations. Source #Defence
Hashtags
@developmentnewsindia · Post #44239 · 30.04.2026 г., 14:05
MDL delivers INS Mahendragiri the 4th & last P-17A stealth frigate built by them to Indian Navy today. Loaded with BrahMos, Barak-8, Naval Gun, RBU-6000 rockets & torpedoes. #Defence
Hashtags
@developmentnewsindia · Post #44237 · 30.04.2026 г., 13:22
DRDO Is Focusing On Directed Energy Weapons For Drone #Defence, Reveals Chairman Samir V Kamat "You can't be firing $3mn missiles at $30,000 drones."
Hashtags
@developmentnewsindia · Post #44236 · 30.04.2026 г., 12:26
1. AGNI-VI awaiting Government Nod 2. LR-AShM Hypersonic Glide Missile in Advance Stages, initial tests soon. 3. DRDO is working on both Hypersonic Glide Missile & Hypersonic Cruise Missile – DRDO Chairman Samir V Kamat #Defence
Hashtags
@developmentnewsindia · Post #44225 · 30.04.2026 г., 09:27
Report- Speaking at the ANI National Security Summit 2.0 in New Delhi, #Defence Secretary Shri Rajesh Kumar Singh said the procurement process for the AMCA is underway and a Request for Proposal (RFP) is expected to be issued soon to shortlisted private sector players. He also indicated that India is also exploring collaboration on sixth-generation fighter aircraft, given the massive investment such programmes require. “We’ve made it clear… that we are interested and we could consider partnering them for a sixth generation fighter program. Let’s see what the response is,” he said.
Hashtags
@developmentnewsindia · Post #44194 · 29.04.2026 г., 14:08
Just in: The DRDO and the Indian Navy jointly and successfully conducted the first 'salvo launch' of the 'Naval Anti-Ship Missile-Short Range' (NASM-SR) from an Indian Navy helicopter platform off the coast of the Bay of Bengal in Odisha. #Defence
Hashtags