从python中的字符串中删除控制字符

发布于 2021-01-29 15:08:27

我目前有以下代码

def removeControlCharacters(line):
    i = 0
    for c in line:
        if (c < chr(32)):
            line = line[:i - 1] + line[i+1:]
            i += 1
    return line

如果要删除多个字符,这是行不通的。

关注者
0
被浏览
81
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    Unicode中有 数百个
    控制字符。如果您要清理来自Web或其他可能包含非ASCII字符的其他来源的数据,则需要Python的unicodedata模块。该unicodedata.category(…)函数返回任何字符的unicode类别代码(例如,控制字符,空格,字母等)。对于控制字符,类别始终以“
    C”开头。

    此代码段从字符串中删除所有控制字符。

    import unicodedata
    def remove_control_characters(s):
        return "".join(ch for ch in s if unicodedata.category(ch)[0]!="C")
    

    unicode类别的示例:

    >>> from unicodedata import category
    >>> category('\r')      # carriage return --> Cc : control character
    'Cc'
    >>> category('\0')      # null character ---> Cc : control character
    'Cc'
    >>> category('\t')      # tab --------------> Cc : control character
    'Cc'
    >>> category(' ')       # space ------------> Zs : separator, space
    'Zs'
    >>> category(u'\u200A') # hair space -------> Zs : separator, space
    'Zs'
    >>> category(u'\u200b') # zero width space -> Cf : control character, formatting
    'Cf'
    >>> category('A')       # letter "A" -------> Lu : letter, uppercase
    'Lu'
    >>> category(u'\u4e21') # 両 ---------------> Lo : letter, other
    'Lo'
    >>> category(',')       # comma  -----------> Po : punctuation
    'Po'
    >>>
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看