Регулярно требуется преобразовать какой-либо текст в максимально совместимый текст для 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
NewPipe
(YouTube Premium)
🆕Обновление
Неофициальный клиент для популярного сервиса YouTube со всеми преимуществами Premium версии. Нет рекламы и доступно фоновое воспроизведение.
⚙️Полная Premium версия, вырезана реклама, доступно скачивание видео и аудио.
#YouTube@pm_plus
#NewPipe@pm_plus
📱Play Market +
⚡️ НАШ ЧАТ
#NewPipe on #Linux, Using Android_translation_layer
https://flathub.org/apps/net.newpipe.NewPipe
Comments
https://news.ycombinator.com/item?id=41963932
#yt
NewPipe x SponsorBlock
A fork of NewPipe with SponsorBlock functionality.
The implementation is still a bit basic but it generally works pretty well.
💡 How can I get this?
Builds will be uploaded in the Releases section. Please download the APK from the newest release and install it on your device.
💡 Why isn't this in upstream NewPipe?
The developer team behind the official NewPipe decided that they do not want to include this kind of functionality in their app. See https://newpipe.schabi.org/blog/pinned/newpipe-and-online-advertising/ and https://github.com/TeamNewPipe/NewPipe/pull/3205 for more information and discussion.
We obviously disagree but we respect their decision and continue to offer SponsorBlock in NewPipe via this fork.
https://github.com/polymorphicshade/NewPipe#newpipe-x-sponsorblock
#newpipe#sponsorblock
NewPipe Releases (unofficial) - NewPipe's GitHub releases
The APK sent here cannot be installed over F-Droid's one because they use different signing keys (details)
This pull request adds an experimental SponsorBlock integration, the fork's apk is linked there
👉🏼https://t.me/newpipe_releases👈🏼
💡 read this as well: YouTube video hosting alternatives
https://t.me/NoGoolag/2284
#newpipe#youtube#alternatives
📡@libreware📡@nogoolag
BraveNewPipe
A libre lightweight streaming front-end for Android
Due to restrictive project policy, the #NewPipe team refuses to add platforms that they find offensive. This fork (BraveNewPipe) will not be as restrictive. As long as the platforms work in the spirit of free speech, they could be integrated.
Nevertheless, platforms that promote pornography or other degrading things will NOT be included here.
Contribute
This fork will focus only on integrating other platforms. Unrelated patches will be rejected for now.
Feel free to suggest which alternative platforms should be included. Any contribution (development/testing/bug report) is greatly appreciated.
Which additional platforms are supported?
Bitchute
Rumble
Other features not found in NewPipe
-NewPipe x Sponsorblock into this fork
-searchfilters: in the action menu of the search page you can now change the search behavior for the actual search. The supported content/sort filters depend on the service
https://github.com/bravenewpipe/NewPipe
Download
https://github.com/bravenewpipe/NewPipe/releases
#yt#video#streaming
#java#4k#android#bandcamp#download_videos#newpipe#peertube#soundcloud#translation#video#watch#youtube_video
NewPipe is a free, open-source Android app for ad-free streaming and downloading videos/audio from YouTube, SoundCloud, PeerTube and more, with background play, pop-up mode, subscriptions without accounts, and no Google tracking for full privacy. The team is rewriting the code for a modern, stable version—download nightly builds to try new features early. This benefits you by saving data/battery, enabling offline/multitasking use, and protecting your data on any device.
https://github.com/TeamNewPipe/NewPipe