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

Резултати

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

Пребарај: #serbia

当前筛选 #serbia清除筛选
Orizzonti Politici

@orizzontipolitici · Post #980 · 07.01.2021 г., 10:54

Con il nostro giro del mondo, ora voliamo in #Serbia. 🇺🇸Con l’elezione di Biden negli Usa, le politiche statunitensi sono destinate a cambiare. I loro effetti si spingeranno sino ai Balcani, intaccando anche lo strano equilibrismo che costituisce il tratto peculiare della nazione tradizionalmente considerata egemone nell’area: la Serbia. 🇷🇸Visto l’appoggio concesso a Trump per il suo disinteresse sulla questione aperta del Kosovo, il presidente serbo Aleksander Vučić – già costretto ad affrontare i movimenti interni che denunciano una torsione autoritaria – dovrebbe essere annoverato tra gli sconfitti. 📥Non è così facile in Serbia, dove la politica estera si basa su quattro pilastri: i rapporti con Usa, Ue, ma anche Cina e Russia. Mantenere buoni rapporti con una nazione così influente è prerogativa essenziale. Nonostante tutto, l’elezione di Biden rischia di minare questo equilibrio. ▶️vai all'articolo

Hashtags

BAZUKA

@jbazuka · Post #302 · 24.09.2022 г., 12:07

🇷🇸#SerbiaМарш за семейные ценности в Белграде⚠️☝️ 💬 Люди продолжают выходить на шествия в поддержку семейных ценностей, даже после победы над гей-парадом, который смогли отменить люди, показав свою решительность в этом вопросе.

Hashtags

BAZUKA

@jbazuka · Post #250 · 11.08.2022 г., 11:33

🇷🇸#SerbiaСербские фермеры вышли на забастовку⚠️☝️ 💬 Дороги, ведущие к правительственным учреждениям в Нови-Саде и Воеводине, перекрыты из-за повышения стоимости топлива. 💬 «Если вы не выполните наши требования, то мы заблокируем всю страну!»

Hashtags

RTDocumentary

@rtdocumentary · Post #746 · 12.05.2022 г., 09:20

‘This is like Hitler’s Kristallnacht when he killed about 90 people, and they want to kill much more.’ In an exclusive interview with RT Documentary, Emir Kusturica compared European politics to Hitler's actions. The director is sure it is impossible to cancel Russian culture. Moreover, he calls on his colleagues to open a new chapter of Russian history: ‘We must bring Dostoevsky to the planet, not only to Europe.’ Kusturica is the creator of the Kustendorf Film Festival. More than 500 films from all over the world have been selected for the festival this year. The Russian movie Clear Sky has been awarded the gold. Emir Kusturica is one of the subjects in our new documentary about Russia's friends in Europe, and there are many of them. Will you be waiting for thepremiere? #video#Serbia Follow: https://t.me/rtdocumentary

RTDocumentary

@rtdocumentary · Post #245 · 07.10.2021 г., 10:00

Serbian Woodstock 🎺 #video#Serbia Every year, thousands of revellers gather in a small Serbian town to dance their feet off, immerse themselves in Balkan brass music and feel like characters in a Kusturica movie. It’s the annual trumpet festival in Guca that runs for five days straight. Brass bands come from all over Serbia to compete for the ‘Golden Trumpet’ trophy, make a little money and get noticed by industry leaders. The Guca festival was first held in 1961 and has since grown into Serbia’s biggest music event. Brass bands are an essential part of every major event, including births, weddings and funerals. Find out more about the festival and see what it’s like to party in Serbia - https://youtu.be/WwP_AdfNERg Follow: https://t.me/rtdocumentary

POPULAR FRONT

@popularxfront · Post #5789 · 06.04.2026 г., 11:27

🇷🇸#Serbia – 🇭🇺#Hungary: Two backpacks containing what Serbian authorities described as “US-made plastic explosives” were discovered in Kanjiza, a few hundred meters from the TurkStream pipeline linking the town to the Hungarian border. The devices, along with detonators, were found yesterday by the Serbian military and police near the gas infrastructure. Serbian officials have said that they had prior intelligence that a “man with military training from the migrant community” was planning a diversion targeting the pipeline. On the Hungarian side, PM Viktor Orbán convened an emergency defence council, calling it a planned sabotage and warning of threats to energy security ahead of the April 12 elections. The incident has escalated into a political crisis in Hungary, with opposition figures suggesting a possible "false flag" in order to influence the upcoming elections. No arrests have been made, as suspects, motive, and responsibility remain unknown. (via Reuters & CNN)

🇭🇺⛽️🪖Parte de TurkStream será protegido por el Ejército húngaro Fuerzas húngaras se encargarán de la proteccióndel tramo del gasoducto TurkStream en territorio del país, desde Serbia hasta Eslovaquia, declaró el canciller, Peter Szijjarto. Cuatro países, Hungría, Serbia, Turquía y Rusia, acordaron tomar medidas decisivas para proteger el gasoducto, agregó. Anteriormente, el presidente de Serbia, Aleksandar Vucic, informó durante una conversación telefónica con el primer ministro húngaro, Viktor Orban, sobre el hallazgo de una bomba a pocos cientos de metros del gasoducto entre Hungría y Serbia. Según Szijjarto, el último intento de sabotaje "encaja bien en una serie" de acciones de Ucrania contra el suministro energético de Hungría. Los informes preliminares de los servicios serbios apuntan a un inmigrante con formación militar como sospechoso en el incidente con bomba en Serbia. 📷 IA #hungría#serbia#ucrania ——— Únete a la lucha por la verdad en 📱Telegram 📱 YouTube 🫥Odysee 📱X

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