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

Резултати

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

Пребарај: #cryptopolicy

当前筛选 #cryptopolicy清除筛选
Venture Village Wall 🦄

@venturevillagewall · Post #4330 · 07.03.2025 г., 13:00

U.S. Must Lead in Crypto Regulation U.S. Treasury Secretary Bessent emphasizes the need for the U.S. to take a global lead on cryptocurrency. Key points include bringing Bitcoin transactions onshore and ceasing government Bitcoin sales. Notably, the evolving regulatory landscape also aims to foster greater adoption of cryptocurrencies in the U.S. #Crypto#U.S. #Bitcoin#Regulation#SEC#BTC#Blockchain#Innovation#CryptoAdoption#Finance#Bessent#Investment#CryptoPolicy#DigitalAssets#Mainstream#MarketTrends#Tech

Crypto M - Crypto News

@CryptoM · Post #65242 · 12.04.2026 г., 08:25

🚀 Former Bank of China VP Comments on U.S. Crypto Regulation Approach Former Bank of China Vice President Wang Yongli has expressed that the United States' method of classifying and regulating crypto assets warrants examination. According to NS3.AI, Wang Yongli noted that the CLARITY Act guidance document represents a notable advancement. However, he emphasized that nations should tailor their crypto asset regulations to align with their specific circumstances. #BankOfChina#CryptoRegulation#USCrypto#CLARITYAct#WangYongli#CryptoPolicy#FinancialRegulation#Blockchain

Crypto M - Crypto News

@CryptoM · Post #65060 · 10.04.2026 г., 17:27

🚀 Senator Lummis Urges Congress to Pass CLARITY Crypto Bill Before 2030 Senator Cynthia Lummis has called on Congress to expedite the passage of the CLARITY crypto market structure bill, emphasizing its importance as a critical legislative opportunity before 2030. According to NS3.AI, Lummis highlighted the urgency of the situation, framing the bill as a narrowing legislative window rather than a finalized policy measure. Her statement underscores the need for timely action to establish a clear regulatory framework for the cryptocurrency market. #SenatorLummis#CLARITYBill#CryptoRegulation#Cryptocurrency#Congress#Legislation#Blockchain#CryptoPolicy#RegulatoryFramework#CryptoNews

Crypto M - Crypto News

@CryptoM · Post #64785 · 09.04.2026 г., 23:37

🚀 South Korea Implements New Rules for Managing Public-Sector Virtual Assets South Korea has approved a plan to manage 78 billion won, equivalent to approximately $57.7 million, in public-sector virtual assets. According to NS3.AI, the new regulations mandate that any seized or confiscated cryptocurrency from personal wallets must be promptly transferred to an institutional cold wallet, which is not connected to the internet. Additionally, the rules stipulate that private keys and recovery phrases must be controlled by at least two individuals through a split-access arrangement. #SouthKorea#PublicSector#VirtualAssets#Cryptocurrency#Regulations#DigitalAssets#CryptoSecurity#ColdWallet#Blockchain#CryptoPolicy

Venture Village Wall 🦄

@venturevillagewall · Post #4289 · 02.03.2025 г., 19:01

Bitcoin Surges Following Large Whale Activity A Hyperliquid whale profited over $10M after opening positions shortly before the Bitcoin price surge to $90,000. Meanwhile, Donald Trump proposed a U.S. national crypto reserve including XRP, SOL, and ADA, raising concerns about insider trading due to the choice of assets. More details on these developments can be found here: Leviathan News and Wu Blockchain News. #Bitcoin#Crypto#XRP#SOL#ADA#Trump#Whale#Profit#NationalReserve#InsiderTrading#Blockchain#Finance#Investing#MarketTrends#BlockchainNews#CryptoPolicy#DigitalAssets#Fintech#VC#AI

Crypto M - Crypto News

@CryptoM · Post #64854 · 10.04.2026 г., 04:34

🚀 South Korea Proposes Stricter Crypto Transfer Regulations South Korea's Financial Intelligence Unit is set to implement more stringent rules on cryptocurrency transfers. According to NS3.AI, the new regulations will mandate reports on suspicious transactions for low-risk transfers exceeding 10 million won, particularly involving private wallets and overseas exchanges. These low-risk transfers will only be permitted if the sender and receiver are verified as the same individual. Additionally, high-risk transactions will face further restrictions. #SouthKorea#CryptoRegulations#Cryptocurrency#FinancialRegulations#Blockchain#CryptoTransfers#DigitalCurrency#FinTech#CryptoCompliance#CryptoPolicy