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 слични објави

Пребарај: #myth

当前筛选 #myth清除筛选
Sayohatnoma: Bagajsiz!

@bagajsiz · Post #73 · 28.01.2025 г., 23:03

#myth Chetga chiqsang, ba’zi stereotiplar parchalanadi deydiku. Ha afsus koʻpchiligi haqiqat boʻlib chiqadi. Masalan, Uzbekistanni Pakistan deb oʻylash. Bu mif emas, men bilan bir necha marta boʻldi. Nafaqat studentlar, balki teacher koʻpchiligi bilmaydiyam bizni mavjudligimizni.

Hashtags

On dragons The dragon Smej Gorynytsch was terrorizing the region around Kiev during the 11th century. The hero Dobrynja vanquished the dragon ultimately. This story follows the same pattern as Zeus defeating Typhon or Perun destroying Veles. #dragon#myth @EuropeanTribalism

Hashtags

Doniyor Olimjonov English | IELTS

@doniyorieltss · Post #451 · 08.01.2023 г., 05:58

#StudentsQuestionsAnswered#myth Let's debunk one common myth surrounding the word count in IELTS Writing: writing more / fewer words than necessary will lower your score. In the past, there was a fixed penalty for writing fewer words than required, as per instructions. But IELTS abolished that as of 2018, and you will not lose marks for being under word. It is also evident that there is no such thing as an upper limit in IELTS Writing. However, there is still a debate over whether or not going way over the recommended number affects your score. Now, does writing 200-220 words for Task 2 universally mean you will lose marks? NO! It's not the number of words that would lower your score, it is what is associated with it: main ideas that lack development. Clearly, your main ideas need to be developed sufficiently, warranting relevant reason(s), explanation(s), and example(s). This means that you would need at least 5 sentences to write a decent body paragraph, which would probably contain 10-20 words each — if you do the math, you would need to write at least 250 words no matter what! This goes to show that if you were to actually write fewer words than required, your ideas would be left under-developed (Task Response: Band 5-6 as per the band descriptors), which means that it's not being underlength per se that would impact your score — it is its result that does so. However, it's also a matter of the task at hand — whether or not it calls for a lot of words. There are certain questions that you could fully respond to with only 250-270 words, while there are also some that require far more words than necessary, say 500 words. In this case, it is perfectly fine to produce what you might assume is an overly long essay, as slashing this word count could compromise your TR score — you would not be able to fully cover the topic. So think twice before you pounce on my 400-word long essays. There is also an issue of 'redundancy' — writing too many words than necessary language-wise — that ticks off many IELTS Instructors such as myself. I check dozens of essays every week only to find out that most of the words and sentences in them are simply unnecessary. In an attempt to impress the reader, students go out their way to use seemingly high-level words/phrases such as 'due to the fact that' instead of a simple 'because'. I completely disapprove of this practice and argue that efficiency and communication should be prioritized in any type of writing — you should treat your words as if you treat your money. Thus, especially at lower levels (Band 5-6), candidates are highly recommended to keep the word count hovering at 250-300 words. Finally, let me also shed some light on Task 1, which is the part of Writing that doesn't receive the level of attention it deserves. When summarizing a chart/diagram, it is important to understand that there are usually a lot of key features you need to highlight and report. If you want to pull off Task 1, you should cover all those key features fully and clearly (Task Achievement: Band 8). Missing even one of such features would set you up for failure: Task Achievement: Band 4. As such, you might want to care less about how many words you need to write and more about what actually matters. I, for one, never think about the number of words when writing something; I focus on the message — so should you! @ieltsulugbeks

Aesthetica

@Aetatesolis · Post #4109 · 27.03.2025 г., 09:26

🎬 "Cinema is one of the last remaining places that transports us from the realm of the mundane into the numinous." John Bucher Mythblast 2025 #josephcampbell #cinema #myth AETATESOLIS

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