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

Резултати

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

Пребарај: #collocation

当前筛选 #collocation清除筛选
Fluent English™

@English_easyly_learn · Post #1092 · 15.08.2018 г., 08:49

📓IELTS Vocabulary: Word of the day ✅Agreement 👉🏻 COLLOCATIONS ▪️make an agreement We made an agreement not to tell anyone. ▪️sign an agreement The two countries have signed an agreement on military co-operation. ▪️have an agreement They have an agreement that all workers should be union members. ▪️reach/come to an agreement also conclude an agreement (formal) It took the two sides several weeks to reach an agreement. ▪️break/violate an agreement The UN accused the country's leaders of breaking international agreements. ▪️keep/honour an agreement also stick to an agreement (informal) (=do what you have agreed) ▪️be bound by an agreement (=have to obey the conditions of an official agreement) ▪️negotiate an agreement (=discuss particular things in order to reach an agreement) ▪️draft an agreement (=write the conditions of an agreement, which may be changed) ▪️enter into an agreement (formal) (=make an official agreement, which has legal responsibilities) ▪️finalize an agreement (=agree the last part) ▪️an agreement breaks down (=it stops working) 👌🏻Share this with your friends! and help them also IELTS effectively! #Collocation #vocabulary 📓IELTS Vocabulary: Word of the day ✅agonizing also agonising /ˈægənaɪzɪŋ/ adjective 👉🏻 extremely painful The pain was agonizing. 👉🏻 very unpleasant to experience, especially because of involving a difficult choice or a long wait an agonizing decision 👌🏻Share this with your friends! and help them also IELTS effectively! #vocabulary @English_easyly_learn

Journey to Fluency

@fluencyinenglish · Post #7804 · 27.10.2020 г., 07:31

#vocabulary #collocations @ieltsstrategies ♦️Verb + aim 1️⃣ clarify + aim You'll need to clarify the aims and objectives of your project. Make sure you state them clearly at the beginning of your report. 2️⃣ achieve + aim Our organisation is committed to achieving its aims through peaceful means. We totally reject violence as a means of political change. 3️⃣ pursue + aim Some companies pursue their aims in a very ruthless way - with no thought of what they are doing to the environment. 4️⃣ support + aim I support the aims of animal rights activists because I want to see a ban on using animals in experiments. 5️⃣ have + aim He's just drifting. He seems to have no aims in life at all. Would you talk to him? 6️⃣ set out + aim All parents receive a booklet which sets out the school's aims and objectives before their children start their first term. #collocation @ieltsstrategies With the aim of + adjective 1️⃣ With the aim of + employment My sister went to Valencia last year with the aim of finding employment in the hotel industry so that she could improve her Spanish. 2️⃣ With the aim of + awareness This booklet has been produced with the aim of increasing public awareness of AIDS. 3️⃣ With the aim of + dependency A new scheme has been set up with the aim of reducing people's dependency on the welfare state. 4️⃣ With the aim of + relations The police regularly visit schools in run-down inner-city areas with the aim of improving community relations. 5️⃣ With the aim of + homelessness A new charity has been set up with the aim of tackling homelessness among young single men. #collocation @ieltsstrategies ✅ Upper-intermediate Common adjective + aim 1️⃣ clear + aim Before you start this project, it is important to have a clear aim in mind. You really need to know where you're going. 2️⃣ laudable + aim Increasing the state pension is a laudable aim, but I don't think the country can afford it. 3️⃣ long-term + aim Promotion to the first division is the long-term aim of the club, but our immediate aim is to win our next match. 4️⃣ broad + aim I sympathise with the broad aims of the party, but on this particular issue I'm afraid I have to disagree. 5️⃣ underlying + aim Although the President is here on an official visit, I think the underlying aim is to promote trade. 6️⃣ sole + aim He's a selfish sort of person. His sole aim in life seems to be to make money. 7️⃣ common + aim This company will only be successful if people work together with common aims. #collocation @ieltsstrategies

Journey to Fluency

@fluencyinenglish · Post #7576 · 14.03.2020 г., 06:30

#vocabulary #collocations @ieltsstrategies ♦️Verb + aim 1️⃣ clarify + aim You'll need to clarify the aims and objectives of your project. Make sure you state them clearly at the beginning of your report. 2️⃣ achieve + aim Our organisation is committed to achieving its aims through peaceful means. We totally reject violence as a means of political change. 3️⃣ pursue + aim Some companies pursue their aims in a very ruthless way - with no thought of what they are doing to the environment. 4️⃣ support + aim I support the aims of animal rights activists because I want to see a ban on using animals in experiments. 5️⃣ have + aim He's just drifting. He seems to have no aims in life at all. Would you talk to him? 6️⃣ set out + aim All parents receive a booklet which sets out the school's aims and objectives before their children start their first term. #collocation @ieltsstrategies With the aim of + adjective 1️⃣ With the aim of + employment My sister went to Valencia last year with the aim of finding employment in the hotel industry so that she could improve her Spanish. 2️⃣ With the aim of + awareness This booklet has been produced with the aim of increasing public awareness of AIDS. 3️⃣ With the aim of + dependency A new scheme has been set up with the aim of reducing people's dependency on the welfare state. 4️⃣ With the aim of + relations The police regularly visit schools in run-down inner-city areas with the aim of improving community relations. 5️⃣ With the aim of + homelessness A new charity has been set up with the aim of tackling homelessness among young single men. #collocation @ieltsstrategies ✅ Upper-intermediate Common adjective + aim 1️⃣ clear + aim Before you start this project, it is important to have a clear aim in mind. You really need to know where you're going. 2️⃣ laudable + aim Increasing the state pension is a laudable aim, but I don't think the country can afford it. 3️⃣ long-term + aim Promotion to the first division is the long-term aim of the club, but our immediate aim is to win our next match. 4️⃣ broad + aim I sympathise with the broad aims of the party, but on this particular issue I'm afraid I have to disagree. 5️⃣ underlying + aim Although the President is here on an official visit, I think the underlying aim is to promote trade. 6️⃣ sole + aim He's a selfish sort of person. His sole aim in life seems to be to make money. 7️⃣ common + aim This company will only be successful if people work together with common aims. #collocation @ieltsstrategies

English Speakers

@English_Speakers · Post #3261 · 08.02.2018 г., 12:43

🔻#collocation #Pure 💎 Pure language ....... لغة فصحى 💎 Pure water ............. ماء عذب 💎 Pure man ............... رجل نقي القلب او السريرة 💎 Pure mathematics رياضيات بحتة 💎 Pure tea ................. شاي فاخر 💎 Pure gold ............... ذهب خالص 💎 Pure Jordanian ..... أردني أباً عن جد 💎 Pure angels ........... ملائكة أبرار 💎 Pure sky ................ سماء صافية 💎 Pure alcohol .......... كحول نقي 💎 Pure iron ................ حديد صرف 💎 Pure metaphor ...... استعارة مجردة 💎 Pure profit .............. ربح صافي 💎 Pure monopoly ...... احتكار مطلق @English_Speakers

Неге “процесс” “үдеріс” те, “үрдіс” те емес, процесс болуы керек Көбіміз “Үрдіс”, яғни әдет-ғұрып, салт дәстүрді білдіретін сөзді тенденция орнына қолданып жүрміз. Тенденцияны - көп жерде үрдіс емес, әлдененің үрдіс алуы, үрдіске айналуы /айнала бастауы деп аударған жөн. Әңгіме “үдеріс” жайлы болса, кей контексте “процесс” сөзіне балама бола алады. Тек ол мағынада қолдануға болатын аясы өте тар, мысалы, әлден жүріп жатқан нәрсеге қолдануға болады. “Тарихи үдеріс” мысалы, тарихи процеске емін-еркін балама бола алады. Ал “разработка процесса” деген сияқты сөйлемде қолдану - орынсыз тірлік. Себебі, әлі жоқ нәрсені, дайындауға, бастауға болатын нәрсені үдеріс деуге болмайды. “Технологический процесс”- дегенді “технологиялық үдеріс” деу де тақырыптан хабарсыздыққа мезгейді. Сложные процессы - дегенді “Күрделі үдерістер” деу де қисынсыз. “Күрделі амалдар” (әлдебір мақсаты бар дүние болса), егер мақсатсыз болса — құбылыстар, өзгерістер. Ал кейде “кезең” деп аударуға болады. Мысалы: “После этого, субстанция должна пройти через сложный процесс осушки” - Содан кейін, шикізат күрделі кептіру кезеңінен өтуі тиіс”. Сот процесін “үдеріс” деуге болмайды, ұлтшылдықтан көтің қақ айрылса да, “процесс” боп қалады, әйтпесе, мағынаға қиянат қыласың. Егер “в процессе чего-либо” деген тіркес келсе, яғни процестің өз алдына салмағы жоқ, әлдебір амал-құбылыстың жүзеге асу кезін білдірсе, онда “Пәленше барысында” деуге әбден болады. Тенденцияны үрдіс алу, “үдеріс” деуге болады. Бірақ, кей контексте беталыс, бетбұрыс деген сөздер мағынаны дәлірек ашады. Бұл нені білдіреді? Процесс сөзінің қазақшаға аударылмайтынын ба? - Жоқ, әрине. Әрі мен сізге аударылатынын дәлелдедім. Енді неге процесс қалуы керек? Процесс сөзінің мағыналары көп, сондықтан бір де бір сөз оның орнына жалғыз өзі қонжия алмайды, бұл бір. Оны әр контексте әрқалай аудару үшін қазақшаң өте мықты болуы аз, айтылған сөз төркіні мен контекстін беске білуің керек. Ондай қабілетті кітап оқымайтын жалпақ жұрт тұрмақ, жас филолог маманнан талап ету - жұртты қазақ тілінен бездірумен бірдей. Себебі, әр сөздің салыстырмалы диагностикасын жасау терең зерттеуді, немесе қыруар тәжірибені талап етеді. Оған қазақтың бәрінде уақыт жоқ. Сондықтан, қайсысы қолданылатынын білмесек, контекстін ажырата алмасақ немесе ол белгісіз болса, “тенденция”, “процесс” сөзін сол күйі қалдырған жөн. #контекст#collocation#process#процесс#аударма#процесс