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

Резултати

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

Пребарај: #hacktoberfest

当前筛选 #hacktoberfest清除筛选
python-telegram-bot

@pythontelegrambotchannel · Post #89 · 07.10.2020 г., 20:06

The v13 release is not just a release either, it is also our official announcement of participation in the annual #hacktoberfest. 💻🥨 We know that we're a few days late to the party, but v13 had to get ready before. 😉 This year, the fest is opt-in for projects and we definitely want to opt into taking part in this great event! If you ever thought about starting coding or giving back to your favourite open source repositories, now is the time! Head over to the hacktoberfest website to learn more about it. We already prepared some issues on our repositories and aim towards opening more issues for starters, but feel free to begin a hunt for improvements and fixes by yourself!

python-telegram-bot

@pythontelegrambotchannel · Post #75 · 01.10.2019 г., 05:44

Fellow programmers. Happy #hacktoberfest. This event, hosted over here, is about giving back to open source projects. We encourage you all to check it out and make some contributions. We prepared some issues by ourself, they can be found here, but fear not to take on other issues in our repo. If you have any questions, feel free to ask them away in our chats, we are there to help!

GitHub Trends

@githubtrending · Post #14980 · 20.07.2025 г., 12:30

#html#hacktoberfest CSS exercises help you practice styling web pages by editing HTML and CSS files to match given designs. You can use resources like documentation and Google to complete them, which builds your real-world skills without needing to memorize everything. Practicing this way improves your understanding of CSS, making it easier to create visually appealing, user-friendly websites that load faster and work well on different devices. It also helps you learn how to organize and update styles efficiently, which is important for web development jobs. Using git to save your work encourages good coding habits. This hands-on practice boosts your confidence and prepares you for real projects[1][2][3][4]. https://github.com/TheOdinProject/css-exercises

GitHub Trends

@githubtrending · Post #15196 · 04.10.2025 г., 12:00

#javascript#hacktoberfest#stremio Stremio is an easy-to-use media center app that lets you find, watch, and organize movies, TV shows, live channels, and more from many sources in one place. You can install addons to add content, sync your library across devices, and even download videos for offline viewing. It supports subtitles, Chromecast streaming, and high-quality formats like 4K HDR. Stremio keeps your data safe by running addons remotely and respects your privacy with minimal data collection. This means you get a secure, convenient, and personalized streaming experience without switching apps or worrying about security. https://github.com/Stremio/stremio-web

GitHub Trends

@githubtrending · Post #14646 · 30.04.2025 г., 11:30

#python#erp#hacktoberfest#odoo#python These tools are for Odoo administrators to improve technical features. They include modules like **attachment queue**, **auto backup**, and **audit log**, which help manage files, secure data, and track changes. Other modules like **sentry** and **server action logging** help monitor errors and server actions. These tools make Odoo more efficient and easier to manage, providing benefits like better data security and improved system performance. https://github.com/OCA/server-tools

GitHub Trends

@githubtrending · Post #15378 · 31.12.2025 г., 11:30

#javascript#erp#hacktoberfest#odoo#python OCA/web offers 40+ free addons for Odoo 18 web interface, like dark mode, responsive design, custom calendars, notifications, charts, and tree view improvements with maintainers listed. All pass pre-commit, build, and translation checks, licensed AGPL-3.0 or per module. You gain easy UI enhancements to customize Odoo backend faster, boost usability on mobile/touchscreens, save time on exports/filters, and improve productivity without coding from scratch. https://github.com/OCA/web

GitHub Trends

@githubtrending · Post #14645 · 29.04.2025 г., 12:00

#java#amazon#aws#aws_sdk#hacktoberfest#java The AWS SDK for Java 2.0 is a major upgrade offering non-blocking I/O for faster performance, customizable HTTP implementations, and easier integration with AWS services like S3 and DynamoDB through Maven, helping developers build scalable applications efficiently. https://github.com/aws/aws-sdk-java-v2

GitHub Trends

@githubtrending · Post #14658 · 01.05.2025 г., 15:00

#java#cloud_native#hacktoberfest#java#kubernetes#reactive Quarkus is a Java framework designed for cloud-native and container-first applications, making Java apps start up much faster and use less memory, which lowers cloud costs. It supports both traditional and reactive programming styles in one framework, so you can develop efficiently without learning new tools. Quarkus uses build-time processing and can compile to native images for even better performance. It integrates popular Java standards and libraries, making development smoother and more enjoyable. This means you can build modern, fast, and cost-effective Java applications easily, especially for Kubernetes and cloud environments[1][2][4][5]. https://github.com/quarkusio/quarkus

GitHub Trends

@githubtrending · Post #15479 · 08.02.2026 г., 14:30

#shell#automation#docker#hacktoberfest#home#iot Home Assistant apps extend your smart home setup with tools like MQTT brokers, MariaDB databases, Duck DNS for secure remote access, file editors, Samba sharing, Zigbee/Z-Wave controllers, and more, all installed easily via the frontend. This benefits you by unifying device control in one app for powerful local automations, better privacy without cloud reliance, no subscriptions, and flexibility across brands—simplifying management even if internet fails. https://github.com/home-assistant/addons

GitHub Trends

@githubtrending · Post #15290 · 11.11.2025 г., 14:30

#python#hacktoberfest#hacktoberfest_accepted#hacktoberfest2021#pywhatkit PyWhatKit is a simple Python library that helps automate everyday tasks like sending WhatsApp messages, sharing images, playing YouTube videos, converting text to handwriting, and more. It works right away with no extra setup and supports the latest Python versions. With PyWhatKit, you can schedule messages, control your PC remotely, and even turn images into ASCII art. This saves time and makes it easy to handle routine jobs, making your daily workflow faster and more efficient. https://github.com/Ankit404butfound/PyWhatKit

123•••56
ПретходнаСтраница 1 од 6Следна