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

Резултати

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

Пребарај: #incidents

当前筛选 #incidents清除筛选
Bali News

@balinews · Post #601 · 04.04.2026 г., 09:25

👮‍♂️ Another social media thrill-seeker in Bali has ended up in an immigration report 📍 A video has gone viral showing a tourist speeding on a motorbike and launching off a well-known cliff near Balangan Beach straight into the ocean. 🛵 He tied the bike with a rope to keep it from falling into the water, but it didn’t help — the rented vehicle was badly damaged, and the offender refused to pay for the damages. #incidents@BaliNews

Hashtags

Bali News

@balinews · Post #531 · 25.11.2025 г., 13:50

👮‍♂️ A major scandal is unfolding in Bali 📰 According to local reports, russian influencer Sergey Domogatsky, known in Indonesian social media as Mr. Terimakasih (“Mr. Thank You”), is suspected of running a large-scale real-estate investment scheme. Amid the ongoing police investigation, Domogatsky has already left Indonesia. 👮‍♂️ Authorities say there are 30 complaints filed by 29 foreign nationals against the 40-year-old Russian. Victims claim he collected funds under the pretext of investing in luxury property developments on the island — projects that were never completed. 💸 The estimated losses amount to 80 billion Indonesian rupiah, roughly 5 million USD. 🔎 The situation continues to develop as Bali police carry on with the investigation. #incidents@BaliNews

Hashtags

Car News

@car_news · Post #1763 · 26.12.2025 г., 10:45

🚕Waymo robotaxis are back at the center of a scandal 📍 This time, the vehicles caused chaos on the streets of San Francisco. 🚥 The autonomous taxis use the traffic-light system for navigation, so when it goes down, route planning breaks as well. ⛔ For several hours, Waymo cars stood on the roads like bricks, blocking other drivers from getting through. Is rise of the the machines beginning? #driverless#incidents@Car_News

Car News

@car_news · Post #1741 · 12.12.2025 г., 13:33

😰Three Waymo robotaxis caused a “standoff” and blocked a street in San Francisco 📰 In the northern part of San Francisco, three Waymo autonomous taxis got stuck on a narrow street, completely blocking traffic. Two cars lightly collided while trying to maneuver, after which both went into emergency mode, and the third stopped right in front of them, creating a full traffic jam. 😤 Because of this, residents couldn’t leave their driveways and had to wait for company engineers to intervene and resolve the situation. All vehicles were empty — no passengers were inside. 💬 Waymo commented on the incident, calling it a “learning moment” for improving their autonomous driving system. #driverless#incidents@Car_News

Bali News

@balinews · Post #363 · 21.03.2025 г., 12:41

😱 А very impressive python crawled onto Seminyak beach for a rest yesterday 🐍 It was not allowed to rest, though – despite its status as a public beach, the snake was politely but firmly asked to leave. @BaliNews #places#incidents#Seminyak

Bali News

@balinews · Post #340 · 04.03.2025 г., 12:35

🗺63 bogus investors kicked out of Bali, 111 more await deportation 📰 The Immigration Service conducted Operation Wira Waspada from January 14 to February 21, 2025, together with the police and the Investment Coordination Board (BKPM). 🕵️‍♂️ During the operation, about 520 foreign nationals were found to have used investor visas to enter Bali although they were in the country for other purposes. Most of these foreigners came from China, Russia, Pakistan, India and Australia and were engaged in trading and consulting businesses. 💸 Due to such practices, Indonesia has lost investments worth about 1.6 trillion IDR. @BaliNews #incidents#realestate#investment

Voir de ses propres yeux

@voir_yeux · Post #12790 · 04.05.2026 г., 21:28

🇩🇪 Plus de 20 personnes ont été blessées à des degrés divers lorsqu’une voiture a percuté des personnes dans le centre de Leipzig (est de l'Allemagne), tandis que deux morts ont été signalés. C’est ce qu’a déclaré le chef des pompiers de la ville, Axel Schuh. Deux personnes ont été grièvement blessées, elles ont immédiatement reçu les premiers soins avant d’être transportées en soins intensifs. [...] En outre, nous avons aussi une vingtaine de blessés, a-t-il indiqué, cité par le journal Leipziger Volkszeitung. #incidents#allemagne#voiture#victimes

Voir de ses propres yeux

@voir_yeux · Post #12784 · 04.05.2026 г., 16:08

🇩🇪 Au moins deux personnes ont été tuées lorsqu’une voiture a percuté un groupe de personnes dans le centre de Leipzig (est de l’Allemagne). C’est ce qu’a rapporté le journal Berliner Zeitung, citant son correspondant sur place. Deux autres personnes ont été grièvement blessées, tandis que plusieurs autres ont subi des blessures moins graves. Selon les premières informations, l’accident s’est produit dans le centre historique de Leipzig, sur la principale rue commerçante de la ville. #incidents#allemagne#voiture#victimes

International News

@intnewsagency · Post #8541 · 17.03.2026 г., 06:24

Key Events of Monday, March 16 Bailiffs seized 32.1 billion rubles from Yuzhuralzoloto. Near Moscow, 61 drones were shot down within 24 hours. The Israeli army launched an operation against Hezbollah in Lebanon. Telegram fined 35 million rubles for incomplete removal of banned content. A powerful solar flare threatens a geomagnetic storm. The Ministry of Culture announced personnel changes. Gas prices rose in Moscow. Medvedev returned to ATP top 10. #Russia#InternationalNews#Incidents#Culture#Sports The main news of Russia and the world ishere.