Регулярно требуется преобразовать какой-либо текст в максимально совместимый текст для 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
X 上的医学资源
Here are some of my favorite posts and threads related to #meded from 2023!
一位医学博士列出了他在 X 上关注到的最喜欢医学相关帖子和主题,并分享了这个线程,很有趣。其中还有不同的主题 Thread,相关医学史介绍等,每位都值得学习和关注。
从疫情开始我就一直有关注「病毒学」「炎症」「疾病」等主题,医学/疾病相关是每个人都应该点亮的技能和值得延展的知识图谱,关乎我们的身体。加上 X 作为最好的学术内容和动向展示平台,我们可以更容易地扩展。
Reference
- 医学网站 Read by QxMD
- 大流行的社会科学反思
- Here's 100 tweets on ADHD
#medical
🏥🇺🇸US HOSPITALS OVERWHELMED BY WAR VETERANS
🔹 VA hospitals at 180% capacity treating wounded soldiers from Iran war 🚑
🔹 Medical staff working 16-hour shifts, mandatory overtime across nation 👩⚕️
🔹 PTSD cases skyrocket 400% among returning troops and military families 🧠
🔹 Mental health crisis: suicide hotlines report 200% increase in calls 📞
🔹 Civilian hospitals forced to treat veterans as VA system collapses 🏥
🔹 Medical supply shortage hits ICUs as resources diverted to military 💊
Healthcare system breaking under war casualties burden 😟⚕️
#healthcare#veterans#PTSD#medical
@america
➡️🔥We are constantly told to "battle" cancer. "Fight hard." "Beat it."‼️⬇️
🟡My dad did the exact opposite. He surrendered.
➡️He looked at a Stage 4 diagnosis and said, "I'm not spending my last days in a war zone."
🟡He bought an RV. He went fishing. He hiked the National Parks.
🟡He completely dropped the rope. He stopped fighting the disease and started enjoying the sunset.
🟡18 months later, the doctors called his 60% tumor shrinkage an "anomaly."
🟡It turns out, sometimes the body can't heal when it's locked in a constant state of combat and fear.
⚡️Peace is a severely underrated therapeutic.👏
Credit: Sandra🔥
🔗Source
👉ℙ𝕌ℝ𝕀𝕋𝔸ℕ
❤️
#people#medical#health#nature#facts
FastWave Medical Secures $19M Funding
FastWave Medical has raised $19 million to advance its development of innovative and cost-effective intravascular lithotripsy systems aimed at treating calcific artery disease. Learn more: FastWave Medical
#Funding#Medical#HealthTech#Innovation#Intravascular#Lithotripsy#ArteryDisease#FastWaveMedical#Investment#Healthcare
St Michael's Operations is a nonprofit organization of Catholic laymen that provides Church protection and emergency response, donates medical supplies to chapels and parishes, provides cost effective training and now provides humanitarian aid and the corporal works of mercy to our clientele and our countrymen. Primarily located in California and Arizona it has a branch pending in Wisconsin and is entering into negotiations for opening a Texas branch.
We have donated thousands of man hours, and thousands of dollars in equipment. We have protected rosary rallies during tense political standoffs in the vicinity. We have provided on scene BLS medical assistance on multiple occasions. We have removed multiple after hours trespassers, as well as removed those who have disrupted the Mass.
We are an all volunteer force and we depend on join fees, membership dues, Church sponsorship and the generosity of our fellow man in order to conduct operations. In Fiscal year 2023 we are looking to set up a fully functional disaster response team in order to help provide relief wherever tragedy strikes such what we saw with East Palestine, Ohio. Additionally we are looking to send three of our most dedicated volunteers to get some advanced hands on training with the EPS League's Hard Skills intensive. We want to sponsor them as much as possible so as to prevent undue financial burden on these good men. This training will go towards hardening the security posture of our chapels and parishes and give us the ability to provide proper protection to important members of the Ecclesiastical hierarchy such as the Bishops, especially during Holy Week.
If it is on your heart and you are disposed, please consider donating. You will of course receive a statement regarding your donation in order to write it off of your taxes.
Our current fundraising goal is a minimum of $20,000 by July.
God bless you and St Michael protect you. #fundraising#security#nonprofit#training#help#team#catholic#medical
https://venmo.com/code?user_id=3195413498691584121