Python将英文标点替换成空格

    def remove_symbols(sentence):
        """
        Remove numbers and symbols from ASCII
        """
        import string
        del_estr = string.punctuation + string.digits  # ASCII 标点符号,数字
        replace = " "*len(del_estr)
        tran_tab = str.maketrans(del_estr, replace)
        sentence = sentence.translate(tran_tab)
        return sentence

首先导入string包,需要调用string.punctuation常量和string.digits常量

maketrans() 方法用于创建字符映射的转换表,对于接受两个参数的最简单的调用方式

        第一个参数是字符串,表示需要转换的字符

        第二个参数是字符串,表示转换的目标。

maketrans函数要求替换的长度相同,所以进行" "*len(del_estr)

translate() 方法根据参数table给出的表(包含 256 个字符)转换字符串的字符,要过滤掉的字符放到 deletechars 参数中

猜你喜欢

转载自blog.csdn.net/hang916/article/details/83832381
今日推荐