删除特殊字符并将空格替换为“”

2024-06-02 11:12:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试创建一个可以在URL中显示的目录。我想确保它不包含任何特殊字符,并用连字符替换任何空格。你知道吗

from os.path import join as osjoin
def image_dir(self, filename):
    categorydir = ''.join(e for e in  str(self.title.lower()) if e.isalnum())
    return "category/" + osjoin(categorydir, filename)

它正在删除特殊字符,但是我想用.replace(" ", "-")来交换带有连字符的空格


Tags: pathfromimportself目录urlosas
3条回答

您可以创建此函数并调用remove \u special \u chars(s)来执行此操作:

def __is_ascii__(c):
    return (ord(c) < 128)


def remove_special_chars(s):
    output = ''

    for c in s:
        if (c.isalpha() and __is_ascii__(c)) or c == ' ':
            output = output + c
        else:
            if c in string.punctuation:
                output = output + ' '

    output = re.sub(' +', ' ', output)
    output = output.replace(' ', '-')

    return output

它将删除中的每个非ASCII字符和每个元素字符串.标点符号

编辑: 此函数将替换中的每个元素字符串.标点符号如果需要,可以在else语句中将“”替换为“”,以合并标点元素前后字符串的两部分。你知道吗

最好的方法可能是使用^{}函数,该函数将任何字符串作为输入,并返回与URL兼容的字符串,您的不是URL,但它会起到作用,例如:

>>> from django.utils.text import slugify
>>> slugify(' Joel is a slug ')
'joel-is-a-slug'

为什么不使用quote函数呢?你知道吗

import urllib.parse

urlllib.parse.quote(filename.replace(" ", "-"), safe="")

相关问题 更多 >