파이썬에서 문자열 슬러지 화
"slug"가 무엇인지 " slugify"문자열을 "slugify"하는 가장 좋은 방법을 찾고 있으며 현재 솔루션은 이 레시피를 기반으로 합니다.
나는 그것을 약간 변경했습니다.
s = 'String to slugify'
slug = unicodedata.normalize('NFKD', s)
slug = slug.encode('ascii', 'ignore').lower()
slug = re.sub(r'[^a-z0-9]+', '-', slug).strip('-')
slug = re.sub(r'[-]+', '-', slug)
누구든지이 코드에 문제가 있습니까? 잘 작동하지만 내가 뭔가를 놓치고 있거나 더 나은 방법을 알고 있습니까?
라는 이름의 python 패키지가 있습니다 python-slugify
.
pip install python-slugify
다음과 같이 작동합니다.
from slugify import slugify
txt = "This is a test ---"
r = slugify(txt)
self.assertEquals(r, "this-is-a-test")
txt = "This -- is a ## test ---"
r = slugify(txt)
self.assertEquals(r, "this-is-a-test")
txt = 'C\'est déjà l\'été.'
r = slugify(txt)
self.assertEquals(r, "cest-deja-lete")
txt = 'Nín hǎo. Wǒ shì zhōng guó rén'
r = slugify(txt)
self.assertEquals(r, "nin-hao-wo-shi-zhong-guo-ren")
txt = 'Компьютер'
r = slugify(txt)
self.assertEquals(r, "kompiuter")
txt = 'jaja---lol-méméméoo--a'
r = slugify(txt)
self.assertEquals(r, "jaja-lol-mememeoo-a")
참조 더 많은 예제를
이 패키지는 귀하가 게시 한 것보다 약간 더 많은 기능을 수행합니다 (소스를 살펴보면 파일 하나에 불과합니다). 프로젝트는 여전히 활성 상태입니다 (원래 답변 2 일 전에 업데이트되었으며 4 년이 지난 후 (2017-04-26 마지막 확인), 여전히 업데이트 됨).
주의 :라는 이름의 두 번째 패키지가 있습니다 slugify
. 둘 다 가지고있는 경우 가져 오기 이름이 같으므로 문제가 발생할 수 있습니다. 방금 이름 slugify
이 지정된 것은 내가 빠르게 확인한 모든 작업을 수행하지 않았습니다. "Ich heiße"
가되었습니다 "ich-heie"
(이어야 함 "ich-heisse"
) . pip
또는 사용할 때 올바른 것을 선택해야합니다 easy_install
.
유니 코드 지원을 위해 여기 에서 유니 코드 양식 을 설치 하십시오.
pip install unidecode
# -*- coding: utf-8 -*-
import re
import unidecode
def slugify(text):
text = unidecode.unidecode(text).lower()
return re.sub(r'[\W_]+', '-', text)
text = u"My custom хелло ворлд"
print slugify(text)
>>> 내 사용자 정의 khello-vorld
awesome-slugify 라는 파이썬 패키지가 있습니다 .
pip install awesome-slugify
다음과 같이 작동합니다.
from slugify import slugify
slugify('one kožušček') # one-kozuscek
Django 에서 잘 작동 하므로 왜 좋은 범용 slugify 함수가 아닌지 모르겠습니다.
그것에 문제가 있습니까?
문제는 ascii 정규화 라인에 있습니다.
slug = unicodedata.normalize('NFKD', s)
It is called unicode normalization which does not decompose lots of characters to ascii. For example, it would strip non-ascii characters from the following strings:
Mørdag -> mrdag
Æther -> ther
A better way to do it is to use the unidecode module that tries to transliterate strings to ascii. So if you replace the above line with:
import unidecode
slug = unidecode.unidecode(s)
You get better results for the above strings and for many Greek and Russian characters too:
Mørdag -> mordag
Æther -> aether
def slugify(value):
"""
Converts to lowercase, removes non-word characters (alphanumerics and
underscores) and converts spaces to hyphens. Also strips leading and
trailing whitespace.
"""
value = unicodedata.normalize('NFKD', value).encode('ascii', 'ignore').decode('ascii')
value = re.sub('[^\w\s-]', '', value).strip().lower()
return mark_safe(re.sub('[-\s]+', '-', value))
slugify = allow_lazy(slugify, six.text_type)
This is the slugify function present in django.utils.text This should suffice your requirement.
Unidecode is good; however, be careful: unidecode is GPL. If this license doesn't fit then use this one
A couple of options on GitHub:
- https://github.com/dimka665/awesome-slugify
- https://github.com/un33k/python-slugify
- https://github.com/mozilla/unicode-slugify
Each supports slightly different parameters for its API, so you'll need to look through to figure out what you prefer.
In particular, pay attention to the different options they provide for dealing with non-ASCII characters. Pydanny wrote a very helpful blog post illustrating some of the unicode handling differences in these slugify'ing libraries: http://www.pydanny.com/awesome-slugify-human-readable-url-slugs-from-any-string.html This blog post is slightly outdated because Mozilla's unicode-slugify
is no longer Django-specific.
Also note that currently awesome-slugify
is GPLv3, though there's an open issue where the author says they'd prefer to release as MIT/BSD, just not sure of the legality: https://github.com/dimka665/awesome-slugify/issues/24
You might consider changing the last line to
slug=re.sub(r'--+',r'-',slug)
since the pattern [-]+
is no different than -+
, and you don't really care about matching just one hyphen, only two or more.
But, of course, this is quite minor.
Another option is boltons.strutils.slugify
. Boltons has quite a few other useful functions as well, and is distributed under a BSD
license.
참고URL : https://stackoverflow.com/questions/5574042/string-slugification-in-python
'Programing' 카테고리의 다른 글
LINQ의 표준 편차 (0) | 2020.10.16 |
---|---|
svn diff : 바이너리 유형으로 표시된 파일 (0) | 2020.10.16 |
공유 기본 설정의 모든 키를 반복하는 방법은 무엇입니까? (0) | 2020.10.16 |
WELD-000072 비활성화 범위를 선언하는 관리 Bean은 비활성화 가능해야합니다. (0) | 2020.10.16 |
Android의 Chrome에서 글꼴 크기 조정 (0) | 2020.10.16 |