Risposte:
Non hai bisogno di espressioni regolari. Python ha un metodo stringa incorporato che fa quello che ti serve:
mystring.replace(" ", "_")
Sostituire gli spazi va bene, ma potrei suggerire di andare un po 'oltre per gestire altri caratteri ostili all'URL come punti interrogativi, apostrofi, punti esclamativi, ecc.
Si noti inoltre che il consenso generale tra gli esperti SEO è che i trattini sono preferiti ai caratteri di sottolineatura negli 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!"))
Django ha una funzione 'slugify' che lo fa, così come altre ottimizzazioni ottimizzate per gli URL. È nascosto nel modulo defaultfilters.
>>> from django.template.defaultfilters import slugify
>>> slugify("This should be connected")
this-should-be-connected
Questo non è esattamente l'output richiesto, ma IMO è migliore per l'utilizzo negli URL.
Questo tiene conto dei caratteri vuoti diversi dallo spazio e penso che sia più veloce dell'uso del remodulo:
url = "_".join( title.split() )
\x8f)
Utilizzando il remodulo:
import re
re.sub('\s+', '_', "This should be connected") # This_should_be_connected
re.sub('\s+', '_', 'And so\tshould this') # And_so_should_this
A meno che tu non abbia più spazi o altre possibilità di spazi bianchi come sopra, potresti semplicemente voler usare string.replacecome altri hanno suggerito.
Sorprendentemente questa biblioteca non è ancora stata menzionata
pacchetto python chiamato python-slugify, che fa un ottimo lavoro di slugify:
pip install python-slugify
Funziona così:
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")
Sto usando il seguente codice per i miei URL amichevoli:
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
Funziona bene anche con i caratteri Unicode.
Python ha un metodo integrato su stringhe chiamato sostituisci che viene utilizzato come segue:
string.replace(old, new)
Quindi useresti:
string.replace(" ", "_")
Ho avuto questo problema qualche tempo fa e ho scritto codice per sostituire i caratteri in una stringa. Devo iniziare a ricordare di controllare la documentazione di Python perché hanno funzioni integrate per tutto.
OP sta usando python, ma in javascript (qualcosa da fare attenzione poiché le sintassi sono simili.
// 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"
Puoi provare questo invece:
mystring.replace(r' ','-')
perl -e 'map { $on=$_; s/ /_/; rename($on, $_) or warn $!; } <*>;'
Abbina e sostituisci spazio> carattere di sottolineatura di tutti i file nella directory corrente
slugifynon fornisce l'output desiderato.