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

Резултати

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

Пребарај: #zig

当前筛选 #zig清除筛选
GitHub Trends

@githubtrending · Post #15187 · 02.10.2025 г., 11:30

#zig TigerBeetle is a powerful, highly reliable database built specifically for financial transactions, designed to handle huge volumes with safety and speed. It ensures that once a transaction is confirmed, it cannot be lost, even if hardware fails or data gets corrupted. It uses advanced techniques like replication, checksums, and fault-tolerant consensus to keep data safe and available. TigerBeetle is much faster and more efficient than traditional databases, making it ideal for mission-critical financial systems that need to process thousands of transactions per second without errors or downtime. This means you get a secure, fast, and stable platform for managing money transfers and accounts reliably. https://github.com/tigerbeetle/tigerbeetle

Hashtags

GitHub Trends

@githubtrending · Post #14855 · 23.06.2025 г., 12:00

#zig Ghostty is a fast, feature-rich terminal emulator that combines speed, native platform integration, and modern features without compromise. It supports multi-window, tabs, and split panes, with GPU-accelerated rendering using Metal on macOS and OpenGL on Linux for smooth performance. Ghostty is highly compatible with existing shells and software, making it a drop-in replacement. It offers rich theming, ligature support, and advanced developer features that enable more interactive command-line applications. Its native UI and cross-platform design provide a polished, efficient terminal experience that enhances productivity and usability for both users and developers. https://github.com/ghostty-org/ghostty

Hashtags

Mexc Crypto Signals Pumps Trading Kucoin

@mexc_signals_pumps_trading · Post #920 · 08.04.2024 г., 16:06

🔥GEM ANNOUNCEMENT🔥 #ZIG/USDT: Spot Signal (Exchange: Bybit, Bitget, MEXC, Gate.Io) Technical Analysis: #ZIG is pumping exactly from the support zone and now breaking a resistance trendline. We can see bullish momentum in it right now because technically this coin looks very strong. You people can buy and hold it now because bull run is going on and we can get good profits in it

Hashtags

The Devs

@thedevs · Post #2030 · 12.12.2022 г., 10:48

Ziglings, learn the Zig programming language by fixing tiny broken programs. #resources#zig @thedevs @thedevs_zig https://thedevs.link/6itjmW

AIGC

@aigcrubbish · Post #313 · 14.04.2026 г., 19:17

Zig 0.16.0 released Zig 编程语言发布了 0.16.0 版本。这是历时 8 个月的工作成果,包含了来自 244 位贡献者的 1183 次提交。 本次发布最引人注目的特性是引入了“作为接口的 I/O”(I/O as an Interface)。除此之外,语言本身、编译器、构建系统、链接器、模糊测试工具链等也都有显著的改进和增强。 原文链接:https://lwn.net/Articles/1067634/ #编程语言#Zig#软件开发#技术更新 #AIGC Read more

AIGC

@aigcrubbish · Post #91 · 04.12.2025 г., 01:25

Cro provides commentary on LWN's Zig asynchronicity article Loris Cro 发布了一个 YouTube 视频,详细讨论了 LWN 上一篇关于 Zig 新 `Io` 接口的文章中使用的术语。他指出,原文在术语使用上存在一些不清晰或混淆之处,例如将“非阻塞 I/O”称为“异步 I/O”,有时又将异步性与并发性混为一谈。对于想精确了解 Zig 的设计方法及其背后动机的读者,Cro 的视频值得一看。 原文链接:https://lwn.net/Articles/1049158/ #编程#Zig#异步编程#术语解释 #AIGC Read more

GitHub Trends

@githubtrending · Post #15207 · 09.10.2025 г., 13:30

#zig#3d_game#cubyz#game#procedural_generation#sandbox#sandbox_game#voxel#voxel_game#zig Cubyz is a 3D voxel sandbox game like Minecraft, letting you explore unlimited height and depth with far view distances. It has a unique crafting system where you can try making any tool, and the game figures out what it is. It runs on Windows and Linux, written in the Zig programming language for better performance. You can easily download and run it or compile it yourself if you want the latest version. The game is open-source, so you can contribute by adding code, gameplay features, or textures following simple guidelines. This means you get a flexible, creative game with ongoing improvements and community support. https://github.com/PixelGuys/Cubyz