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

Резултати

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

Пребарај: #spelling

当前筛选 #spelling清除筛选
1 English learning materials

@englishmeta1 · Post #518 · 11.03.2026 г., 06:17

Some useful spelling rules – Part I ========================== 🟣 Rule 1 🌼When a weak verb ends in a short vowel + consonant, the final consonant is not doubled to form the past tense, unless the accent falls on the last syllable. 🔹Budget – budgeted (NOT budgetted) 🔹Offer – offered (NOT offerred) 🔹Benefit – benefited (NOT benefitted) 🔎 Notes Worship is an exception to this rule. Its past tense is formed by doubling the final consonant. 🔹Worship – worshipped (NOT worshiped) 🌼If the accent falls on the last syllable, the consonant is doubled even if the word ends in a short vowel + consonant. So we have 🔹Occur – occurred (NOT Occured) 🔹Transfer – transferred (NOT transfered) 🔹Begin – beginning (NOT begining) 🌼If the final consonant is ‘l’, it is always doubled. 🔹Travel – travelled 🔹Level – levelled 🔸Parallel is an exception to this rule. Its past tense is paralleled (NOT parallelled). Nowadays traveled is also considered correct. ------------------------------------- 🔵 Rule 2 🌼Short monosyllables always double their final consonant. 🔹Shop – shopping 🔹Let – letting 🌼‘ie’ and ‘ei’ The general rule is ‘i’ before ‘e’ except after ‘c’. Examples are: siege, believe, friend But receive, deceive, ceiling etc. 🌼There are several exceptions to this rule. Reign, neighbor, heir, seize, leisure, weird 🌼Dis and mis Never double the ‘s’ of these prefixes. When a second ‘s’ occurs it is the first letter of the next syllable. Examples are: dismiss (not dissmiss), misplace (not missplace) 🔹dissent (dis-sent), misspell (mis-spell) 🌼‘us’ and ‘ous’ Nouns end in ‘us’. Adjectives end in ‘ous‘. So we have: 🔹Census, genius (nouns) 🔸Jealous, tremendous, 🚥🚥🚥🚥🚥🚥 #spelling #teamjimmy #sirjimmy

English With Natives*

@sirJimmy · Post #29641 · 12.11.2022 г., 13:59

📝SPELLING📝 Please readthe email from Anna to Olga below. Then find and correct the sevenspelling mistakes. Hi Olga I’m writing to thank you for meetting me and looking after me in Bratislava. I had a really great time and after traveling all the way from Warsaw it was wonderful to see you waiting for me when I arrived. I thought Bratislava was beautiful and now I’m hopping that you will visit me in Warsaw soon. I’m glad I remembered to bring my camera (I’m always forgeting it) because I’ve got some really great photos, which I’m attaching. I think the one of us standing in front of the castle just before it openned is the best. I also really enjoyed the shoping and the restaurants and I’m sure I’ve got fater as a result of all that wonderful food! Please start planing your visit to Warsaw soon – I’m really looking forward to seeing you! Love, Anna #Spelling #Common_Mistakes #Teamjimmy @Sirjimmy

English With Natives*

@sirJimmy · Post #29336 · 03.08.2022 г., 14:29

📝SPELLING📝 Please readthe email from Anna to Olga below. Then find and correct the sevenspelling mistakes. Hi Olga I’m writing to thank you for meetting me and looking after me in Bratislava. I had a really great time and after traveling all the way from Warsaw it was wonderful to see you waiting for me when I arrived. I thought Bratislava was beautiful and now I’m hopping that you will visit me in Warsaw soon. I’m glad I remembered to bring my camera (I’m always forgeting it) because I’ve got some really great photos, which I’m attaching. I think the one of us standing in front of the castle just before it openned is the best. I also really enjoyed the shoping and the restaurants and I’m sure I’ve got fater as a result of all that wonderful food! Please start planing your visit to Warsaw soon – I’m really looking forward to seeing you! Love, Anna #Spelling #Common_Mistakes #Teamjimmy @Sirjimmy

English With Natives*

@sirJimmy · Post #28740 · 07.04.2022 г., 05:17

📝SPELLING📝 Fill the gaps with the correct form of words. ➕➕➕➕➕➕➕➕➕➕➕ 🌀A- /əˈkɒmədeɪt/ to provide enough space for somebody or something I don’t have enough bedrooms to __ you. 🌀B- /əkˈnɒlɪdʒ/ to accept that something is true I __ that I could have tried harder. 🌀C- /əˈdres/ details of where somebody lives or works and where letters, etc. can be sent. Please write your __ in block capitals. #Spelling #Common_Mistakes #Teamjimmy @Sirjimmy

RedFox Branding

@redfoxuz · Post #1004 · 13.05.2020 г., 00:36

«…» va “…”. Qo‘shtirnoqlar farqi Bugungi postda grafik jihatdan qo‘shtirnoqlarni qo‘llash haqida qisqagina ma’lumot bo‘ladi. Demak qoida shunday: — Rus tilida «вот так» yoki kamdan-kam hollarda „вот так“ — Ingliz tilida “like this” O‘zbek tili uchun: — Lotin yozuvida „bunday“ — Kirill yozuvida «бундай» Kelib chiqishiga ko‘ra, bu «…» — fransuzcha, bu “…” — inglizcha, bu „…“ — nemischa qo‘shtirnoq. Klaviatura kombinatsiyalari: « — Alt + 0171 » — Alt + 0187 “ — Alt + 0147 ” — Alt + 0148 „ — Alt + 0132 #spelling#blog@blogfolio

Language Trivia 🤔

@languagetrivia · Post #341 · 17.11.2024 г., 10:38

Listen to the audio and choose the correct spelling for this famous sauce: A) Worchestershire sauce B) Wosterchire sauce C) Worstershire sauce D) Worcestershire sauce Follow 🌎@languagetrivia for more interesting questions #pronunciation#spelling

Learn RCRussian🤍💙❤️

@learnrcrussian · Post #4777 · 30.05.2025 г., 11:47

👋Приветствую! Скучно is spelled with ЧН but how is it pronounced? 🔻Words containing the ЧН combination are usually pronounced as they are spelled. However, there are exceptions: • Конечно [ka-nesh-na] - of course • Скучно [skush-na] - boring • Нарочно [na-rosh-na] - deliberately • Яичница [yi-ish-ni-tsa] - fried eggs • Скворечник [skva-resh-nik] - birdhouse • Пустячный [pus-tyash-nyj - trivial, insignificant 🔻In feminine patronymics ending in -ична, it's pronounced like this: Никитична [ni-ki-tish-na], Ильинична [il'-yi-nish-na]. ❗️However, скучно can also be pronounced like [skuch-na] not [skush-na], according to the pronunciation in St Petersburg. #reading_rules #spelling 😎RCRussian | Support | Boost

Learn RCRussian🤍💙❤️

@learnrcrussian · Post #4387 · 24.03.2025 г., 09:00

👋Приветствую! Понедельник ... • Нехотя [ne-kha-tya] Meaning: Unwillingly, reluctantly, inadvertently 🔻It implies a lack of enthusiasm or a feeling of being forced to do something. 🔻It comes from negative particle не + verb хотеть(to want). ❌ Не хотя ✅ Нехотя • Нехотя приступаем к работе, товарищи! [ne-kha-tya pris-tu-pa-yem k ra-bo-te, ta-va-ri-shchi] Reluctantly, let's begin our work, comrades! 🎧🗣👇 ▶️Неохотно (Synonym) #useful_vocabulary #spelling #MondayMood 😎 Stay with @learnRCRussian

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