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

Резултати

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

Пребарај: #gstratechange

当前筛选 #gstratechange清除筛选
IRAS

@irassg · Post #710 · 12.12.2023 г., 02:29

#GSTRateChange Consumers who come across cases of unjustified price increases of essential goods or services that use the GST increase as a cover can provide their feedback to the Committee Against Profiteering (CAP) at www.cap.gov.sg/shareyourfeedback. All feedback submitted will be reviewed by CAP, and further investigated if necessary, to identify businesses that may have engaged in unjustified price increases on the pretext of the GST increase. For more information, please visit CAP’s website.

IRAS

@irassg · Post #699 · 05.12.2023 г., 02:30

#GSTRateChange Only GST-registered businesses can charge GST from their effective date of GST registration. You can check if a business is GST-registered at https://go.gov.sg/gst-registered-business-search. Non-GST registered businesses are not allowed to charge GST.

IRAS

@irassg · Post #676 · 28.11.2023 г., 02:34

#GSTRateChange Do you know how much GST will be charged, for transactions that span the rate change? It all depends on when the invoice is issued, whether payment is made and if the goods/services have been delivered/performed. Read on for some scenarios you might find yourself in! 👉🏼More info on the transitional rules for the rate change

IRAS

@irassg · Post #666 · 21.11.2023 г., 02:31

#GSTRateChange From 1 Jan 2024, you should see price displays from GST-registered businesses, with GST charged at 9%. Prices that are quoted, whether written or verbal, should be GST-inclusive so that you know the final price pay upfront. 👉🏼 Click here for more info on price displays

IRAS

@irassg · Post #654 · 07.11.2023 г., 07:32

#GSTRateChange With the second step of the GST rate change approaching, IRAS reminds all businesses to ensure that their systems are ready to incorporate the new 9% GST rate with effect from 1 Jan 2024 and to take active steps to avoid rate change errors during implementation. 👉🏼Click here for more on getting your business ready for the second rate change and common rate change errors to avoid

IRAS

@irassg · Post #558 · 19.06.2023 г., 03:31

#GSTRateChange Businesses are strongly encouraged to start preparation early for a smooth transition to the GST rate of 9% on 1 Jan 2024. Here are 3 main things for businesses to do, ahead of the second GST rate change. 👉🏼Click here for more information on preparing for the rate change

IRAS

@irassg · Post #305 · 13.12.2022 г., 02:40

#GSTRateChange PSA: Only GST-registered businesses can charge GST from their effective date of GST registration. You can check if a business is GST-registered at https://go.gov.sg/gst-registered-business-search. Non-GST registered businesses are not allowed to charge GST.

IRAS

@irassg · Post #285 · 06.12.2022 г., 06:00

#GSTRateChange Do you know how much GST will be charged, for transactions that span the rate change? It all depends on when the invoice is issued, whether payment is made and if the goods/services have been delivered/performed. Read on for some scenarios you might find yourself in! 👉🏼Click here for more info on the transitional rules for the rate change

IRAS

@irassg · Post #733 · 31.12.2023 г., 06:44

#GSTRateChange Heading to the 24-hour store to grab some post-NYE party essentials in the wee hours of 1 Jan 2024? #DidYouKnow that you may only be charged GST at 8% on your purchase, if it is the supplier’s normal accounting practice to treat sales made after midnight as sales of the preceding day! 👉🏼Click here for more info on the transitional rules for the rate change

IRAS

@irassg · Post #334 · 31.12.2022 г., 02:31

#GSTRateChange Making a run to the 24-hour store in the wee hours of 1 Jan?#DidYouKnow you may only be charged GST at 7% on your purchase, if it is the supplier’s normal accounting practice to treat sales made after midnight as sales of the preceding day! 👉🏼 Click here for more info on the transitional rules for the rate change

IRAS

@irassg · Post #725 · 22.12.2023 г., 06:30

Navigate the right GST rate to pay for transactions spanning the rate change with new mummy and her bestie! 💁‍♀️💡 A transaction is considered to span the GST rate change if one or two of the following events takes place wholly or partially on/after 1 Jan 2024: - The issuance of invoice by supplier - The receipt of payment by supplier - The delivery of goods or performance of services More info at go.gov.sg/irasgst-rc-consumers #GST#GSTRateChange#skit#iras#irassg

IRAS

@irassg · Post #723 · 20.12.2023 г., 09:10

🎵 We carry through, do what we need to do~ Yes, I’m a GST-registered business just like you 🎵 Here are 3 key things GST-registered businesses need to prepare for the 2024 GST rate change: 1) Update systems to incorporate 9% GST from 1 Jan 2024 2) Prepare price displays to reflect 9% GST from 1 Jan 2024 3) Understand transitional rules to apply the correct GST rate for transactions spanning 1 Jan 2024 Learn more at go.gov.sg/irasgst-rc-businesses #GST#GSTRateChange#iamjustlikeyou#iras#irassg