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

Резултати

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

Пребарај: #earthquake

当前筛选 #earthquake清除筛选
Marwa Osman/MidEaStream

@Marwa_OsmanLB · Post #3061 · 17.08.2024 г., 19:47

A powerful 7.4 magnitude earthquake has struck 107 km ESE of Petropavlovsk-Kamchatsky, Russia, near the Kamchatka region. Local authorities are closely monitoring the situation due to the risk of significant aftershocks and potential tsunamis. #Earthquake#Russia

Interesting Planet 🌍

@interesting_planet_facts · Post #707 · 07.09.2025 г., 20:22

🌎 After a 2010 earthquake in Haiti, a pig named "Lucky" survived buried under rubble for 27 days. He lived by eating charcoal and licking moisture from debris until rescue workers pulled him out alive. ✨ #survival⚡#animals⚡#earthquake 👉subscribe Interesting Planet ​

Interesting Planet 🌍

@interesting_planet_facts · Post #1048 · 17.11.2025 г., 22:11

🌎 The 1755 Lisbon earthquake was one of the most destructive natural catastrophes in European history. The quake, followed by a tsunami and fires, destroyed much of Lisbon and killed up to 50,000 people. Its impact led to major advances in seismology and influenced Enlightenment thinking about disasters. ✨ #earthquake⚡#tsunami⚡#history 👉subscribe Interesting Planet 👉more Channels ​

Interesting Planet 🌍

@interesting_planet_facts · Post #900 · 12.10.2025 г., 22:11

🌎 An enormous tsunami struck the Indian Ocean on December 26, 2004 after a magnitude 9.1 earthquake off Sumatra. Waves up to 30 meters high inundated coasts in 14 countries, killing over 230,000 people and displacing millions, making it one of the deadliest natural disasters in recorded history. ✨ #tsunami⚡#earthquake⚡#history 👉subscribe Interesting Planet 👉more Channels ​

Interesting Planet 🌍

@interesting_planet_facts · Post #807 · 24.09.2025 г., 15:11

🌎 Trapped under debris for 17 days after a 2015 Nepal earthquake, Pemba Tamang survived by drinking muddy water dripping from rubble and eating small snacks. He emerged with only minor injuries after nearly 2½ weeks underground, making it one of the longest earthquake survival cases recorded. ✨ #survival⚡#earthquake⚡#resilience 👉subscribe Interesting Planet 👉more Channels ​

Amazing Geography 🌍

@amazingeo · Post #506 · 10.12.2025 г., 20:31

🌍 The 2018 Sulawesi earthquake in Indonesia triggered a rare "soil liquefaction," turning solid ground into a flowing sludge that swallowed entire neighborhoods beneath muddy waves. ✨ #disasters⚡#earthquake⚡#liquefaction⚡#geography⚡#nature⚡#earth 👉subscribe Amazing Geography 👉more Channels ​

Amazing Geography 🌍

@amazingeo · Post #433 · 04.11.2025 г., 12:31

🌍 Earthquakes under the ocean can create tsunamis—giant waves traveling at jet speed. A tsunami may cross an entire ocean before reaching land with just minutes’ warning. ✨ #tsunami⚡#earthquake⚡#hazards⚡#geography⚡#nature⚡#earth 👉subscribe Amazing Geography 👉more Channels ​

Amazing Geography 🌍

@amazingeo · Post #359 · 11.10.2025 г., 15:31

🌍 The 1811–1812 New Madrid earthquakes in the central United States were so powerful they briefly made the Mississippi River flow backward, reshaping the landscape far from any plate boundary. ✨ #disaster⚡#earthquake⚡#river⚡#geography⚡#nature⚡#earth 👉subscribe Amazing Geography 👉more Channels ​

Google Facts™ [ ️@googlefactss🌎]

@googlefactss · Post #40448 · 31.12.2025 г., 19:01

The 2011 Japan earthquake (8.9 magnitude) made Earth spin faster, shortening the day by 1.8 microseconds. It moved Japan’s main island 8 feet and shifted Earth’s axis by 6.5 inches. The 2010 Chile quake (8.8) and 2004 Sumatra quake (9.1) also shortened the day by small amounts. Earthquakes change Earth’s mass, making it spin quicker like a figure skater. 🌍⏱️ [Read more] @googlefactss#Earthquake#DayLength#EarthRotation

Interesting Planet 🌍

@interesting_planet_facts · Post #1138 · 17.12.2025 г., 18:11

🌎 The Tōhoku earthquake and tsunami struck Japan on March 11, 2011, with a magnitude 9.0 quake and waves up to 40 meters. This disaster caused over 15,000 deaths, triggered the Fukushima nuclear accident, and shifted the Japanese coast by up to 2.4 meters. ✨ #earthquake⚡#tsunami⚡#fukushima 👉subscribe Interesting Planet 👉more Channels ​

12
ПретходнаСтраница 1 од 2Следна