【问题标题】:How to convert string to seo-url?如何将字符串转换为 seo-url?
【发布时间】:2012-01-04 08:11:56
【问题描述】:

我想将重音字符串转换为 seo-url ...

例如: "Le bébé (de 4 ans) a également un étrange "rire"" to : "le-bebe-de-4-ans-a-egalement-un-etrange-rire"

有什么解决办法吗?

谢谢!

【问题讨论】:

    标签: python string url unicode seo


    【解决方案1】:

    这是我用的:

    def _doStringSEOptiomization(objectName,pageName,lang,objectId):
    """
    Prende in input il nome di un'offerta e svolge dei passi:
    1- Trasforma tutte le variazioni delle vocali
       in vocali normali
    2- Attraverso una serie di REGEX, elimina i caratteri non desiderati e torna 
       una stringa da inserire in un link adatto ai motori di ricerca e alle indicizzazioni
    """
    
    try:
        import re #importo il modulo per le REGEX
        Speaker.log_debug(GREEN("core.ws_site.do_sites_offers_data_redux._doStringSEOptiomization() input: objectName=%s, pageName=%s, lang=%s, objectId=%s" % (objectName,pageName,lang,objectId)))
    
        #mappa dei caratteri html-entity e unicode
        vocalMap = { 'a' : ['à','á','â','ã','ä','å','æ','à','á','â','ã','ä','å','ā','æ'],
                     'e' : ['è','é','ê','ë','è','é','ê','ë','ē'],
                     'i' : ['ì','í','î','ï','ì','í','î','ï','ī'],
                     'o' : ['ò','ó','ô','œ','õ','ö','ò','ó','ô','œ','õ','ö','ō'],
                     'u' : ['ù','ú','û','ü','ù','ú','û','ü','ū']
                    }
    
        objectName = objectName.lower() #trasformo la stringa di partenza in caratteri minuscoli
    
        for vocale, lista in vocalMap.iteritems(): #per ogni elemento della mappa avrà una chiave ed una lista
            for elemento in lista: #itero su tutti gli elementi della lista
                objectName = objectName.replace(elemento,vocale) #sostituisco nel nome dell'offerta, la vocale all' HTML-entity
    
        objectName = objectName.replace("/","-")
    
        objectName = re.sub("[^a-z0-9_\s-]","",objectName)     #######################################
        objectName = re.sub("[\s-]+"," ",objectName)           #strippo tutti i caratteri non voluti:# 
        objectName = re.sub("[\s_]","-",objectName)            #######################################
    
        objectName = pageName+"--"+objectName
        objectName += "-"+lang+"-"+str(objectId) #aggiungo la lingua e l'id dell'offerta
    
    except Exception,s:
        Speaker.log_error("_doStringSEOptiomization(): Error=%s"%RED(s))
    
    return objectName 
    

    你必须适应你的情况。

    【讨论】:

      【解决方案2】:

      这可能(或可能不够)足够:

      import re
      import unidecode
      
      def normalized_id(title):
          title = unidecode.unidecode(title).lower()
          return re.sub('\W+', '-', title.replace("'", '')).strip('-')
      

      【讨论】:

        【解决方案3】:
        >>> a = u'Le bébé (de 4 ans) a également un étrange "rire"'
        >>> r = unicodedata.normalize('NFKD',a).encode('cp1256','ignore')
        >>> r = unicode(re.sub('[^\w\s-]','',r).strip().lower())
        >>> r = re.sub('[-\s]+','-',r)
        >>> print r
        le-bebe-de-4-ans-a-egalement-un-etrange-rire
        

        我使用 cp1256 (latin 1) 来处理重音字符...

        完美!非常感谢!

        【讨论】:

          【解决方案4】:

          如果你身边有 Django,你可以使用它的 defaultfilter slugify(或根据你的需要调整它)。

          【讨论】:

            【解决方案5】:
            [~]$ python
            Python 2.7.1 (r271:86882M, Nov 30 2010, 10:35:34) 
            [GCC 4.2.1 (Apple Inc. build 5664)] on darwin
            Type "help", "copyright", "credits" or "license" for more information.
            >>> import unicodedata
            >>> import re
            >>> def seo_string(x):
            ...     r = unicodedata.normalize('NFKD',x).encode('ascii','ignore')
            ...     r = unicode(re.sub('[^\w\s-]','',x).strip().lower())
            ...     return re.sub('[-\s]+','-',r)
            ... 
            >>> seo_string(u'Le bébé (de 4 ans) a également un étrange "rire"')
            u'le-bb-de-4-ans-a-galement-un-trange-rire'
            

            感谢 django 内置过滤器的出色 slugify,但是它不会像 @doncallisto 发布的解决方案那样用 e 替换 é

            【讨论】:

              【解决方案6】:

              这里有几种方法可以做到这一点:Generating SlugsArmin Ronacher。

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 2018-03-08
                • 2011-11-23
                • 1970-01-01
                • 1970-01-01
                • 2016-04-29
                • 2021-10-13
                • 2015-02-21
                • 2020-12-22
                相关资源
                最近更新 更多