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

Резултати

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

Пребарај: #financialservices

当前筛选 #financialservices清除筛选
AI & Law

@ai_and_law · Post #226 · 27.01.2024 г., 08:04

USA: Bipartisan AI Working Group Formed by Lawmakers Hello everyone! US lawmakers have established a bipartisan "AI Working Group." Focused on artificial intelligence's impact on financial services and housing industries, the group aims to delve into the use of AI in decision-making, product development, fraud prevention, compliance, and its effects on the workforce. The group will explore existing AI regulations and propose new ones that balance the potential benefits and risks. The initiative aligns with President Biden's executive order highlighting the need for managing emerging technologies and their associated risks. #AIWorkingGroup#BipartisanAI#FinancialServices#AIRegulation#TechPolicy**

Crypto M - Crypto News

@CryptoM · Post #65151 · 11.04.2026 г., 13:05

🚀 Lakeview Loan Servicing Reaches $26 Million Settlement Over Data Breach Lakeview Loan Servicing has agreed to a proposed $26 million settlement following a data breach that impacted 2.53 million individuals in the United States. According to NS3.AI, the lawsuit alleges that unauthorized actors gained access to the company's systems, potentially exposing names, Social Security numbers, financial account details, and other personal information. While Lakeview denies any wrongdoing, eligible class members may receive compensation, credit monitoring, and identity protection if the settlement is approved. #DataBreach#Settlement#Privacy#IdentityProtection#FinancialServices#CyberSecurity#USNews

Crypto M - Crypto News

@CryptoM · Post #64777 · 09.04.2026 г., 22:14

🚀 TD Cowen Adjusts Price Targets for Strategy and Sharplink TD Cowen has revised its price target for Bitcoin treasury firm Strategy to $350. According to NS3.AI, the financial services company also initiated coverage on Ethereum treasury company Sharplink with a 'buy' rating and set a price target of $16. TD analysts expressed confidence that Sharplink's staking revenue would be sufficient to cover its operating costs, even if Ethereum's market performance remains subdued. #TDCowen#PriceTarget#Bitcoin#Strategy#Sharplink#Ethereum#StakingRevenue#FinancialServices#Cryptocurrency#InvestmentAnalysis#BTC#ETH

Venture Village Wall 🦄

@venturevillagewall · Post #3380 · 18.12.2024 г., 12:09

Mirabelle Secures $1.05M Funding Mirabelle, specializing in mortgage life financing for seniors, has secured $1.05 million in funding as of December 3, 2024. The service aims to enhance retirement experiences by valuing wealth while allowing seniors to remain in their homes. #Funding#Mortgage#LifeFinance#Seniors#Retirement#Housing#Wealth#FinancialServices#Mirabelle#Finance

Crypto M - Crypto News

@CryptoM · Post #64558 · 09.04.2026 г., 07:57

🚀 BNP Paribas Appoints New Head for Equity Capital Markets in India BNP Paribas has reportedly appointed Abhishek Joshi to lead its equity capital markets division within the investment banking sector in India, according to sources. Bloomberg posted on X, highlighting the strategic move by the bank to strengthen its presence in the Indian market. Joshi's appointment is expected to bolster BNP Paribas's capabilities in managing equity capital market operations, as the bank aims to expand its influence in the region. This decision comes amid increasing competition in the investment banking industry, with global banks vying for a larger share of the Indian market. BNP Paribas's investment banking division has been focusing on enhancing its services and offerings to cater to the growing demands of clients in India. Joshi, with his extensive experience in the field, is anticipated to play a pivotal role in driving the bank's growth strategy forward. #BNPParibas#EquityCapitalMarkets#India#InvestmentBanking#AbhishekJoshi#StrategicMove#FinancialServices#GlobalBanks#MarketExpansion#BankingLeadership

Venture Village Wall 🦄

@venturevillagewall · Post #3419 · 18.12.2024 г., 12:11

Tyme Raises $250M Round #Tyme has successfully raised a substantial $250 million in funding, closing the round on December 17, 2024. For more details, visit Tyme's website. #Funding#Tyme#Investment#Capital#Finance#Business#Technology#Startups#FundingRound#VentureCapital #2024 #Growth#Innovation#CapitalRaising#TechNews#Market#Entrepreneurship#StartUpFunding#FinancialServices

Venture Village Wall 🦄

@venturevillagewall · Post #4205 · 21.02.2025 г., 04:00

FraxUSD Transforms Into Fully Fiat-Backed Stablecoin FraxUSD has transitioned to a fully fiat-backed model with 1:1 redeemability, enhancing its competitive stance in the stablecoin market. It boasts deep DeFi integration, institutional-grade reserves, and generates native yield through sfrxUSD. For a detailed analysis, visit Leviathan News. #FraxUSD#Stablecoin#DeFi#Bitcoin#Crypto#Finance#Blockchain#Tokenomics#DigitalAssets#Investment#Innovation#Yield#Redemption#FinancialServices#MarketTrends#InstitutionalInvesting#OnChain#CryptoNews#VC#Fintech

Venture Village Wall 🦄

@venturevillagewall · Post #3398 · 18.12.2024 г., 12:10

Svakarma Finance Raises $10.4M Svakarma Finance successfully raised $10.40 million in funding on December 13, 2024. For more details, visit their website. #Funding#Finance#Svakarma#Investment#Capital#Startup #2024 #Market#Growth#Innovations#Loans#FinanceTech#DigitalFinance#Fintech#VentureCapital#Equity#FundingRound#FinancialServices#Economy

Venture Village Wall 🦄

@venturevillagewall · Post #3423 · 18.12.2024 г., 12:11

VakıfBank Secures $870M Funding Round VakıfBank has announced a funding round of $870 million, set for November 26, 2024. For more details, visit their official page here. #Funding#VakıfBank#Finance#Investment#FundingRound#Banking#Loans#Capital#Turkey#Business#Economy#November2024#Growth#Market#Assets#InvestmentOpportunities#FinancialServices#InstitutionalInvestors#Debt#Equity

Venture Village Wall 🦄

@venturevillagewall · Post #4029 · 30.01.2025 г., 13:00

From Pet Project to Europe's Top Startup Klarna, founded by three Swedish students in 2005, progressed from an idea into Europe's most valuable startup worth $45.6 billion. Initially losing a school competition, they launched a unique payment service. By offering a secure, easy checkout and features like BNPL, Klarna solved key challenges for sellers and buyers. Despite major fluctuations in valuation, they are now preparing for their IPO. This journey emphasizes resilience in entrepreneurship and the complexities of attracting investments. Read more here. #Klarna#Startup#Europe#FinTech#Payments#BNPL#IPO#Entrepreneurship#Investment#TechInnovation#BusinessGrowth#E-commerce #Sweden#Funding#BusinessModel#TechStartups#FinancialServices#OnlinePayments#Disruption#VentureCapital#AI#Crypto

Venture Village Wall 🦄

@venturevillagewall · Post #3411 · 18.12.2024 г., 12:11

Bay Harbor Re Secures $50M Funding Bay Harbor Re, a reinsurance firm, has announced a funding round of $50 million, set for December 13, 2024. The company focuses on delivering stability and protection tailored to meet the specific needs of its partners. #Reinsurance#Funding#Investment#BayHarborRe#FinancialServices#Insurance#Stability#Protection#Partners#BusinessDevelopment#MarketInsights#RiskManagement#Capital #2024 #Profitability#Growth#InsuranceMarket#CorporateNews#FundingRound

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