programing

공백 공간을 언더스코어로 대체하려면 어떻게 해야 합니까?

bestcode 2022. 11. 27. 11:34
반응형

공백 공간을 언더스코어로 대체하려면 어떻게 해야 합니까?

문자열에서 공백 공간을 밑줄로 대체하여 멋진 URL을 만들고 싶습니다.예를 들어 다음과 같습니다.

"This should be connected" 

될 것 같다

"This_should_be_connected" 

저는 파이썬을 장고와 함께 사용하고 있습니다.정규 표현으로 해결할 수 있나요?

규칙적인 표현은 필요 없어요.Python에는 스트링 메서드가 내장되어 있어 필요한 작업을 수행할 수 있습니다.

mystring.replace(" ", "_")

공백 치환도 괜찮지만 물음표, 아포스트로피, 느낌표 등 다른 URL 호스트 문자를 처리하는 것이 좋습니다.

또한 SEO 전문가들 사이에서는 URL에서 밑줄을 치는 것보다 대시를 사용하는 것이 일반적입니다.

import re

def urlify(s):

    # Remove all non-word characters (everything except numbers and letters)
    s = re.sub(r"[^\w\s]", '', s)

    # Replace all runs of whitespace with a single dash
    s = re.sub(r"\s+", '-', s)

    return s

# Prints: I-cant-get-no-satisfaction"
print(urlify("I can't get no satisfaction!"))

이것은 공백 이외의 문자를 고려하기 때문에 사용하는 것보다 빠르다고 생각합니다.re모듈:

url = "_".join( title.split() )

Django는 이를 수행하는 'slugify' 기능과 다른 URL 친화적인 최적화 기능을 가지고 있습니다.디폴트 필터 모듈에 숨겨져 있습니다.

>>> from django.template.defaultfilters import slugify
>>> slugify("This should be connected")

this-should-be-connected

요청하신 출력은 아니지만 IMO는 URL에서 사용하는 것이 좋습니다.

사용방법re모듈:

import re
re.sub('\s+', '_', "This should be connected") # This_should_be_connected
re.sub('\s+', '_', 'And     so\tshould this')  # And_so_should_this

위와 같이 공백이 여러 개 있거나 공백이 있을 수 없는 한 다음을 사용할 수 있습니다.string.replace남들이 제안했듯이

문자열 치환 메서드 사용:

"this should be connected".replace(" ", "_")

"this_should_be_disconnected".replace("_", " ")

놀랍게도 이 라이브러리는 아직 언급되지 않았다.

python-python-pythonify라는 이름의 python 패키지는 다음과 같은 작업을 상당히 잘 수행합니다.

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") 

Python은 다음과 같이 사용되는 replace라는 문자열에 내장된 메서드를 가지고 있습니다.

string.replace(old, new)

따라서 다음을 사용할 수 있습니다.

string.replace(" ", "_")

얼마 전에 이 문제가 있어서 문자열에 문자를 바꾸는 코드를 작성했습니다.Python 문서에는 모든 기능을 내장하고 있기 때문에 잊지 않고 확인해야 합니다.

친근한 URL에 다음 코드를 사용하고 있습니다.

from unicodedata import normalize
from re import sub

def slugify(title):
    name = normalize('NFKD', title).encode('ascii', 'ignore').replace(' ', '-').lower()
    #remove `other` characters
    name = sub('[^a-zA-Z0-9_-]', '', name)
    #nomalize dashes
    name = sub('-+', '-', name)

    return name

유니코드 문자에서도 정상적으로 동작합니다.

mystring.replace (" ", "_")

이 값을 임의의 변수에 할당하면 동작합니다.

s = mystring.replace (" ", "_")

디폴트로는 mystring은 이것을 가지지 않습니다.

대신 다음을 시도해 볼 수 있습니다.

mystring.replace(r' ','-')

OP는 python을 사용하고 있지만 javascript(구문이 비슷하므로 주의해야 할 사항)로 되어 있습니다.

// only replaces the first instance of ' ' with '_'
"one two three".replace(' ', '_'); 
=> "one_two three"

// replaces all instances of ' ' with '_'
"one two three".replace(/\s/g, '_');
=> "one_two_three"
x = re.sub("\s", "_", txt)
perl -e 'map { $on=$_; s/ /_/; rename($on, $_) or warn $!; } <*>;'

현재 디렉토리에 있는 모든 파일의 밑줄과 space > 를 일치시킵니다.

언급URL : https://stackoverflow.com/questions/1007481/how-to-replace-whitespaces-with-underscore

반응형