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

Резултати

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

Пребарај: #wastemanagement

当前筛选 #wastemanagement清除筛选
EKOLOG.UZ| ENG

@ekologuzenglish · Post #11054 · 03.01.2026 г., 10:00

📢 Official Statement According to information shared on our Telegram channel, the situation in front of House No. 69, Beruniy Street, Samarkand caused serious dissatisfaction among local residents. For a long time, the household waste collection area was not cleaned, and the containers were not emptied regularly. As a result, the surrounding environment deteriorated, trash spread around, unpleasant odors appeared, and sanitary standards were violated. ✅ Actions taken: The area in front of House No. 69 on Beruniy Street has been completely cleaned. “Maroqand Obod” LLC will ensure timely waste removal and monitor the area regularly. 🟢 Note: Thanks to residents’ complaints and public oversight, prompt measures were taken. Maintaining a clean environment is important for every citizen. #Samarkand#CleanCity#WasteManagement#PublicOversight☘️Read the latest environmental news on the @ekologuz page. Follow us and send your suggestions and wishes via @eklguz_bot Instagram | Facebook | Twitter | Sayt | Youtube.

Venture Village Wall 🦄

@venturevillagewall · Post #3640 · 21.12.2024 г., 10:23

Hauler Hero Secures $10M Funding Hauler Hero has raised $10 million in funding to enhance its waste management software solution. This platform aids waste haulers in optimizing operations, boosting efficiency, and cutting costs. The funding round closed on December 19, 2024. 🔗Learn more #Funding#WasteManagement#Software#Efficiency#CostReduction#HaulerHero

Crypto M - Crypto News

@CryptoM · Post #65431 · 13.04.2026 г., 07:30

🚀 Japan Considers Remote Pacific Island for Nuclear Waste Disposal Site Japan is reportedly considering a remote Pacific island as a potential location for a nuclear waste disposal site. Bloomberg posted on X that the proposal aims to address the country's ongoing challenges with nuclear waste management. The island's isolation is seen as a strategic advantage, minimizing risks to populated areas. This move comes amid Japan's efforts to enhance its nuclear waste disposal infrastructure, ensuring long-term environmental safety. The proposal is still in its early stages, with further assessments required to evaluate the site's suitability and potential environmental impact. #Japan#NuclearWaste#PacificIsland#EnvironmentalSafety#WasteManagement#NuclearDisposal#Infrastructure#EnvironmentalImpact

Venture Village Wall 🦄

@venturevillagewall · Post #4066 · 04.02.2025 г., 13:00

$7.17M Funding for Thromboinflammatory Solutions Key funding rounds for innovative companies: - Aplagon: $7.17M for thromboinflammatory disease treatments. Learn more - Dxcover: $6.20M targeting liquid biopsy and AI for cancer detection. Learn more - Vetigenics: $6M to enhance pet cancer treatments with targeted antibody therapies. Learn more - Atma Sciences: $5.49M funding announced. Learn more - Semeris: $4.36M for AI-driven legal document review solutions. Learn more - Nala Earth: $3.97M focusing on corporate biodiversity impacts and compliance. Learn more - Laclarée: $3.65M funding round completed. Learn more - Hopia: $3.65M to improve healthcare planning via AI. Learn more - OFFROAD: $1.56M for road and public space management solutions. Learn more - Beans: $1.46M aimed at reducing waste through new product offerings. Learn more #Funding#Thromboinflammatory#Cancer#AI#LiquidBiopsy#PetHealth#LegalTech#Biodiversity#Healthcare#WasteManagement#VC

Venture Village Wall 🦄

@venturevillagewall · Post #3665 · 21.12.2024 г., 11:00

Funding News: December 2024 🚀 Major funding rounds announced: - Alvie: $2.19M for HUGO digital assistant - Buildpeer: $2.50M for construction project optimization - Island Passage: $2.50M in funding - TIXiMED: $2.65M for diabetes treatment - The Pad Climbing: $3M for climbing community project - PeptiSystems: $4.07M for peptide and oligonucleotide therapeutics - Greenlight Health: $4.20M for data solutions - TripSuite: $5M for agency growth tools - DuckChain: $5M for blockchain solutions - Nexa Finance: $5.04M for investment opportunities - Tenor: $5.40M for management training with AI - Smartr365: $6.33M for mortgage brokerage platform - Astraveus: $7.40M for cell therapies - EditPep: $8.20M in funding - Jrnys: $8.65M for personalized healthcare solutions - Hoji: $8.94M for ecological solutions - Hauler Hero: $10M for waste management software - Trinity College, Dublin: $10.46M in funding - PeproMene Bio: $11M for cancer therapies - Hervolution Therapeutics: $11.70M for immunotherapies For more details, visit the respective websites. #Funding#Healthcare#Biotech#AI#Construction#Therapeutics#WasteManagement#Investment#DigitalAssistant#CellTherapies#EcoDesign#Mortgage#Finance#Diabetes#Peptides#Community#Climbing#Software#PersonalizedHealthcare#Blockchain