Регулярно требуется преобразовать какой-либо текст в максимально совместимый текст для 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
🧾Avoiding paying the tourist tax in Bali will become more difficult
More than a year has passed since the introduction of tourist tax in Bali, but the island's authorities still manage to collect it with great creaking.
🤏 In the first 12 months of the 6.3 million foreign tourists who visited Bali, $10 paid only 2.1 million, that is, every third.
🫡 One of the key problems so far has been poor information for tourists, who simply don't know where and how to pay. Since there are no penalties for non-payment, travelers have no incentive to pay the fee, except moral obligation.
📰 The statistics are likely to change in the near future: according to the authorities, visitors to Bali should be ready to show a QR code, which confirms payment of the tax, more often, especially in popular places, the airport and ports.
@BaliNews
#tourism#taxes
🧾 Nusa Penida's tourist tax will be increased and made electronic
🚤 The authorities of Nusa Penida want to introduce a new tax collection system. Now a tourist compulsory payment is 25,000 Rp upon entry to the island. It is collected at the port immediately upon arrival. The new e-ticket system should make it easier for tourists to pay.
🫰 However, along with the introduction of such a system, the size of the fee itself will increase. The authorities explain this step by the need to develop the island, to make it more convenient for both locals and visitors.
❓ The most intriguing question: "what amount of the fee can we talk about?" is still open.
📈 The target for the tourist tax levy on Nusa Penida is 24.8 billion Indonesian rupiah in 2024, which is more than in 2023 (17.7 billion Indonesian rupiah).
@BaliNews
#taxes#tourism#NusaPenida
James Fishback, a political newcomer hoping to succeed Ron DeSantis as Florida's next Republican governor, has proposed a 50 percent sin tax for all income derived from OnlyFans.
The platform, which has grown in recent years to the point of taking $701 million in dividends from its subscribers in 2024, is known for its large amount of pornographic content.
"If you are an OnlyFans model and you reside in Florida, get ready to pay 50 percent of your income to the state. It is called a sin tax because it's a sin, No. 1," Fishback said.
"But the purpose of a sin tax in economics is to disincentivize and deter a behavior," he continued. "And, yes, as Florida governor I don't want young women who could otherwise be mothers raising families, rearing children, I don't want them to be selling their bodies to sick men online."
#Taxes#Pornography
👂More on Trump's Ear ⚠️
📄Biznes va tadbirkorlik oliy maktabida Rossiya xalq xo‘jaligi va davlat xizmati akademiyasi dotsentining moliyaviy hisob bo‘yicha o‘quv kurslari boshlandi
🇺🇿UZB
Начало учебного курса по финансовому учету с доцентом РАНХиГС в Высшей школе бизнеса и предпринимательства
🇷🇺RU
The beginning of the academic course on financial accounting with a professor from RANEPA at the Graduate School of Business and Entrepreneurship.
🇬🇧ENG
#GraduateSchool#Seminar#Taxes#Finance
Web-site | Telegram | Facebook |Instagram
Billionaire Future: Elon Musk Taxes Could Top $500B
🇺🇸 Elon Musk says he may pay $500B+ in lifetime taxes. A bold claim that reignites the billionaire tax debate. #ElonMusk#Taxes#Tesla
https://coinomedia.com/billionaire-future-elon-musk-taxes-could-top-500b/
Congressman Proposes IRS Abolishment Bill
US Congressman Buddy Carter has introduced a bill to abolish the IRS, aiming to repeal all income, payroll, estate, and gift taxes. This radical tax reform could have significant implications for taxpayers.
Bitcoin price surges to $95,000.
#US#IRS#Taxes#Bitcoin#Crypto
The Washington Post, which is owned by Jeff Bezos, one of the richest men in the world, who has long fought against the right of his employees to form unions and conduct collective bargaining on working conditions, published an article condemning the Democrats for seeking to raise taxes on the wealthiest. Let's try to make surprised faces.
#Media#Taxes#Bezos
👂More on Trump's Ear ⚠️
New IRS Rules for DeFi Brokers Announced
The IRS has implemented new rules requiring DeFi brokers to report income from crypto transactions, similar to traditional financial institutions. Market participants will need to collect user transaction data and file Form 1099 starting January 1, 2027. These changes have sparked criticism, with legal experts arguing that the IRS is overstepping its authority. Some believe the incoming Congress might overturn these regulations.
Read more: Forklog
#US#taxes#DeFi#Crypto#IRS
🇺🇿Rossiya xalq xo‘jaligi va davlat boshqaruvi akademiyasining Iqtisodiy va ijtimoiy fanlar fakulteti iqtisodiyot va moliya kafedrasi dotsenti - Alisen Sakinovich ishtirokida davra suhbati rejalashtirilmoqda.
👩💻Ishtirokchilar: Iqtisodiyot va moliya vazirligi, O‘zbekiston buxgalterlar va auditorlar Milliy Assotsiatsiyasi hamda auditorlik kompaniyalari.
🌎Muhokamaning asosiy mavzusi: “Xalqaro moliyaviy hisobot standartlari, soliqlar va soliqqa tortish”.
___
🇷🇺 Круглый стол c участием Алисена Сакиновича - доцента кафедры Экономики и финансов, факультета Экономических и социальных наук Российской академии народного хозяйства и государственной службы.
🧑💻Участники: Министерство экономики и финансов, Национальная Ассоциация бухгалтеров и аудиторов Узбекистана, а также аудиторские компании.
🌎Главная тема обсуждения: «Международные стандарты финансовой отчетности, налоги и налогообложение»
#GraduateSchool#Roundtable#Taxes#Finance
Web-site | Telegram | Facebook |Instagram
Possible Introduction of Windfall Tax to Cover Budget Deficit
In March, a discussion with Vladimir Putin considered implementing a windfall tax on corporate excess profits to support the budget. RSPP head Alexander Shokhin emphasized that, unlike voluntary business contributions, this tax would systematically target extra earnings based on a formula developed with the Finance Ministry and Andrey Belousov. This measure is viewed as a fair way to fund public expenses.
#Russia#windfalltax#budget#taxes
The main news of Russia and the world ishere.
🛂🇺🇸RECORD 6,700 AMERICANS RENOUNCE CITIZENSHIP
🔹 2025 sees highest exodus in US history as wealthy Americans flee to tax havens overseas 🏝️💰
🔹 Switzerland, Singapore, UAE top destinations with total wealth transfer of $2.3 trillion 📊✈️
🔹 IRS crackdown on overseas accounts drives surge alongside political polarization fears 🏛️⚖️
🔹 Immigration lawyers report 300% increase in consultation calls from high-net-worth clients 📞💸
When the rich start running, what does that say about where we're headed? 🤔💭
American Dream or American Nightmare? You decide 🇺🇸🔥
#USNews#Citizenship#Taxes#WealthFlight
@america
📰 NEWS | Venezuela: Rodríguez Announces Labor, Pension, Tax Reforms
Venezuelan Acting President Delcy Rodríguez announced a set of reforms targeting labor laws, pensions, and taxation. A new commission with representatives from government, business, workers, and pensioners will review labor conditions and social security sustainability.
The government also confirmed a worker income increase scheduled for May 1, though details remain unspecified. Additional measures include drafting a new tax model, reviewing state-owned assets to determine “strategic” sectors, and maintaining state control over hydrocarbons.
The announcements come amid ongoing labor protests over wages and working conditions and follow broader economic reform efforts.
Learn more 👉🏾https://shorturl.at/5Cc26
#LaborLaw#Pensions#Taxes#Wages