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

Резултати

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

Пребарај: #alternatives

当前筛选 #alternatives清除筛选
Libreware

@libreware · Post #1060 · 29.04.2022 г., 04:39

We already have a list of open-source alternatives to mainstream social media platforms like Twitter. Take a look 🕵️‍♀️ https://itsfoss.com/mainstream-social-media-alternaives/ @itsfoss_official #alternatives#social

Libreware

@libreware · Post #1406 · 08.02.2025 г., 00:45

Here are some links about #systemd#alternatives for #Linux in no particular order. Which are your favorite alternatives and distros? https://wiki.gentoo.org/wiki/Comparison_of_init_systems https://suckless.org/sucks/systemd/ https://unixsheikh.com/articles/the-real-motivation-behind-systemd.html https://sysdfree.wordpress.com/ https://nosystemd.org/ https://skarnet.org/software/systemd.html https://the-world-after-systemd.ungleich.ch/ https://ewontfix.com/14/ https://forums.debian.net/viewtopic.php?t=120652 https://www.devuan.org/os/announce/ https://www.devuan.org/os/init-freedom https://thehackernews.com/2019/01/linux-systemd-exploit.html https://judecnelson.blogspot.com/2014/09/systemd-biggest-fallacies.html https://chiefio.wordpress.com/2016/05/18/systemd-it-keeps-getting-worse/ https://systemd-free.artixlinux.org/why.php Some more added here too: https://start.me/p/Kg8keE/priv-sec #systemd#Linux

Libreware

@libreware · Post #933 · 26.04.2021 г., 21:35

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

Libreware

@libreware · Post #1430 · 07.03.2025 г., 04:03

@NoGoolag#browser#alternatives with mitigations, patches etc. Alpha version release March 6, 2025 FireFox browser options - Tor Browser (all) - Mullvad Browser (Desktop) - IronFox (Android) Read the Known Issues section on the gitlab. - LibreWolf (mentally ill devs) Make your own #Firefox with mitigations etc... - Phoenix / wiki - Arkenfox user.js / wiki / gui / user-tool / mobile - Narsil / Narsil Mobile - Betterfox / Betterfox Mobile - pyllyukko - Compare some of the user.js files Chromium based browser Options - Ungoogled Chromium (all) - Cromite (Android, Linux, Windows) Browser extensions - uBlacklist - uBlock Origin or uMatrix (never both) - LibRedirect (setup your instances for each service in the settings) Links to block lists... - Yokoffing - Celenity/Phoenix - FilterLists Set your default search engine to a search proxy - 4get instances - Searx instances Why your favorite browser is not recommended - Celenity Firefox browser comparisons - How to choose a browser for everyday use? - is your browser spyware? - Choose your browser carefully - Browsers and the connections they make compared - Fake Privacy and security Additional reading... - Wiki about extensions - Multiple Extension Conflicts - uMatrix for beginners - Firefox user.js install guide - Arch Linux Firefox Privacy wiki - Bromite (for knowledge purposes) Testing your browser - Fingerprint.com - How to test browsers for spyware - Privacytests browser comparison - Mullvad check - Bromite fingerprint testing - IP Leak - List of test sites A - List of test sites B * Thunderbird users should consider taking a look at Dove - Phoenix's sister project.

Libreware

@libreware · Post #913 · 18.03.2021 г., 16:10

Front-ends for evil sites/platforms: Youtube - Source: https://github.com/iv-org/invidious - Instances: https://api.invidious.io Twitter - Source: https://github.com/zedeus/nitter - Instances: https://github.com/zedeus/nitter/wiki/Instances Twitter+YouTube -Source: https://github.com/ytorg/Yotter -Instances: https://github.com/ytorg/Yotter#public-instances Why do I have to register to use Yotter? Instagram - Source: https://sr.ht/~cadence/bibliogram/ - Instances: https://git.sr.ht/~cadence/bibliogram-docs/tree/master/docs/Instances.md Reddit - Sources: https://github.com/spikecodes/libreddit (1) https://codeberg.org/teddit/teddit (2) - Instances: https://github.com/spikecodes/libreddit#instances (1) https://codeberg.org/teddit/teddit#instances (2) Google Translate - Sources: https://sr.ht/~yerinalexey/gtranslate/ (1) https://git.sr.ht/~metalune/simplytranslate_web (2) - Instances: https://gtranslate.metalune.xyz/ (1) https://translate.metalune.xyz/ (2) Google Search Engine - Source: https://github.com/benbusby/whoogle-search - Instances: https://github.com/benbusby/whoogle-search#public-instances P.S. JavaScript isn't required for any core functionality with these front-ends 📡@NoGoolag📡@Libreware #frontends#yt#alternatives

Libreware

@libreware · Post #1017 · 10.12.2021 г., 14:06

Keeweb : Free Cross-Platform Password Manager Compatible With KeePass. Keeweb webapp is a browser and desktop password manager compatible with KeePass databases. It doesn’t require any server or additional resources. The app can run either in browser, or as a desktop app. The app is quite stable now. Basic stuff, as well as more advanced operations, should be rather reliable. https://github.com/keeweb #keepass#passwords#alternatives 📡@cRyPtHoN_INFOSEC_EN

Libreware

@libreware · Post #967 · 04.07.2021 г., 17:29

The best free Audacity Alternatives https://www.ghacks.net/2021/07/04/the-best-free-audacity-alternatives/ All alternatives listed below lack at least one of the main characteristics of Audacity. They are either only available for one operating system, e.g. Windows, not open source, don't offer the same set of core features, or lack in other departments. Audacity Forks Audacity is an open source project, and developers started to fork the application as soon as the announcement hit the Internet that the project team changed. Forks match all main characteristics of Audacity, but there is no "main" fork yet that all disgruntled developers and users switched to. Here is a link to a promising forks (because it is updated regularly) https://github.com/cookiengineer/audacity Another https://github.com/SartoxOnlyGNU/audacium 📡@nogoolag📡@libreware #alternatives#audacity#audio#editor

Libreware

@libreware · Post #1296 · 27.06.2024 г., 04:30

Adobe just announced new terms that say they will do whatever they want with your content, so here are some alternatives to consider. 3DS Max Blender Acrobat Evince (read) Inkscape (edit multi page) LibreOffice_Draw (create, edit, sign) LibreOffice_Writer (create) Nextcloud LibreSign (sign) Okular (read, annotate, sign) OnlyOffice (read, edit) PDF-Shuffler (merge, arrange, delete) XReader (read) AdobeXD Akira Figma Lunacy Pencil Penpot After Effects Astrofox (audio responsive animations) BlackMagicDesign Fusion (proprietary) HitFilm (proprietary) Natron Animate Blender (3D) Friction Glaxnimate (2D) Synfig (2D) Audition Tenacity Audor LMMS Cinema 4D Blender Fresco Krita Illustrator Inkscape Krita sK1 InDesign Lyx Scribus Lightroom Darktable Raw Therapee Paint Krita MyPaint Photoshop GIMP Krita PremierePro DavinciResolve (proprietary) Kdenlive Olive Video OpenShot Pitivi Shotcut ⚡️Follow Freedom Tech on NOSTR https://t.me/LinuxTechIndex #graphic#editor#Adobe#Alternatives

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