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 слични објави

Пребарај: #veterinarymedicine

当前筛选 #veterinarymedicine清除筛选
VET's HUB ®

@vets_hub · Post #29919 · 18.09.2025 г., 02:13

#2_Aspiration_pneumonia Aspiration pneumonia can occur in animals, particularly in those with underlying health conditions or anatomical abnormalities that predispose them to inhaling foreign material into their lungs. Common causes of aspiration pneumonia in animals include regurgitation, vomiting, anesthesia complications, or neurological disorders affecting swallowing. Symptoms of aspiration pneumonia in animals may include coughing, difficulty breathing, fever, lethargy, loss of appetite, and nasal discharge. Diagnosis typically involves a physical examination, chest X-rays, and sometimes additional tests such as bloodwork or bronchoscopy. Treatment for aspiration pneumonia in animals often includes antibiotics to target the infection, supportive care such as oxygen therapy or intravenous fluids, and addressing the underlying cause of aspiration. In severe cases, hospitalization and intensive care may be necessary. Prevention of aspiration pneumonia in animals involves proper feeding techniques, ensuring they are eating appropriate diets for their health condition, and addressing any underlying medical issues that may predispose them to aspiration. Regular veterinary check-ups and prompt treatment of any respiratory symptoms are important for maintaining the overall health of your pet. #veterinarymedicine https://t.me/vets_hub

Vet_opportunities

@vet_opportunities · Post #334 · 18.02.2026 г., 12:49

🌊🐠 Veterinary Students & New Graduates — Ready to Dive into Aquatic Medicine? The John L. Pitts Aquatic Veterinary Education Scholarship was created to honor reminded Dr. John L. Pitts’ lifelong dedication to advancing aquatic veterinary medicine and mentoring young professionals. Since 2010, this program has helped students and recent graduates explore meaningful careers in aquatic animal health. Each year, selected applicants receive financial support to attend conferences, participate in externships, present research, or carry out small aquatic veterinary projects. It’s more than funding — it’s a doorway into a growing and impactful field. If you’re passionate about fish health, aquaculture, marine species, or aquatic welfare, this is your opportunity to take the next step. Applications open in January and close March 31. Your future in aquatic veterinary medicine could start here. 🌊✨ Link: https://www.wavma.org/scholarships #VeterinaryMedicine #AquaticVeterinary #VetStudents #ScholarshipOpportunity #CareerDevelopment For more scholarships, internships and different Veterinary related opportunities, visit: @vet_opportunities @vet_opportunities @vet_opportunities

Animal Welfare Club

@animalwelfarewecare · Post #99 · 19.02.2026 г., 08:20

🐾 WEBINAR ALERT: Rabies Elimination and Animal Welfare 🐾 Join us for a focused, hard-hitting session featuring leading voices in veterinary medicine, public health, and youth advocacy. Our expert panel will break down the most pressing issues, from emergency shelter response to global rabies elimination strategies. 📅Date: Feb 19 ⏰Time: 2:30 L.T 📍Platform: t.me/aau_ohc 🎤MEET THE PANELISTS: 🔹 Dr. Mesfin Semu Wodajo Graduate of Moscow Veterinary Academy (1994) and Utrecht University (2000). Former Associate Researcher at Tetracore, LLC. 14 years as Chief of Staff at Banfield Pet Hospital. Currently Medical Director & Owner at Upper Marlboro Veterinary Hospital. 🔹 Dr. Alazar Ayele Veterinarian specializing in mobile pet care. Co-founder of Beyond Student for Change initiative. Operates a mobile veterinary clinic to expand access to professional animal healthcare and leads community-based stray dog mass rabies vaccination campaigns. 🔹 Dr. Biruk Eshetu University of Gondar graduate (2015 E.C.). Former founder & president of One Health Innovation Club and VP of Clinical Medicine Club at UoG. Currently Manager of the Animal Welfare and Protection Trauma Shelter, Addis Ababa, where he works extensively with pets and shelter animals. 🔹 Yared Ermiyas DVM Candidate, Co-founder of AAU One Health Club, and Animal Welfare Advocate. 🎙️Format:Live 📲 Set a reminder and join us! 👇 Drop a "👋" in the comments if you'll be there! #RabiesElimination#AnimalWelfare#OneHealth#YouthAdvocacy#Webinar#VeterinaryMedicine#ShelterAndRescue

VET's HUB ®

@vets_hub · Post #30111 · 02.11.2025 г., 03:45

BOOK 𝗦𝗺𝗮𝗹𝗹 𝗔𝗻𝗶𝗺𝗮𝗹 𝗜𝗻𝘁𝗲𝗿𝗻𝗮𝗹 𝗠𝗲𝗱𝗶𝗰𝗶𝗻𝗲 🩺🐈🐕 ✒️ 🔸Richard W. Nelson 🔸C. Guillermo Couto With hundreds of images, step-by-step procedures, and a practical clinical emphasis, Small Animal Internal Medicine, 6th Edition offers the foundation and tools you need to properly recognize, diagnose, and treat small animals with common internal conditions. 📚Elsevier 📖 1608 Pages - 𝗣𝗗𝗙 #internalmedicine#smallanimals#pets#dogs#cats#veterinarymedicine#dvm https://t.me/vets_hub