首页 文章

Python:尝试降低字符串并删除空格以外的非字母数字字符

提问于
浏览
4

我试图删除除字符串空格以外的所有非字母数字字符,但似乎无法弄清楚我是如何排除空格的 . 我现在这样做:

re.sub('[\W_]+', '', text).lower().strip()

但运行我的函数会产生以下结果:

print removePunctuation('Hi, you!')
print removePunctuation(' No under_score!')
hiyou
nounderscore

我希望它在哪里:

hi you
no underscore

那么如何排除空间被替换?

我目前的最佳选择是:

re.sub('[^\s\w]+', '', text).lower().strip().replace('_','')

5 回答

  • 0

    你可以用这个,

    re.sub(r'[^\sa-zA-Z0-9]', '', text).lower().strip()
    

    Example:

    >>> import re
    >>> def removePunctuation(s):
            return re.sub(r'[^\sa-zA-Z0-9]', '', s).lower().strip()
    
    >>> print removePunctuation('Hi, you!')
    hi you
    >>> print removePunctuation(' No under_score!')
    no underscore
    

    OR

    re.sub('(?!\s)[\W_]', '', text).lower().strip()
    
  • -1

    你可能更喜欢列表理解:

    result = ''.join([c for c in myString if str.isalnum(c) or str.isspace(c)])
    
  • 0

    您可以使用str.translate删除标点符号:

    s = 'Hi, you!'
    
    from string import  punctuation
    
    print(s.translate(None,punctuation).lower())
    hi you
    

    对于python3:

    s = 'Hi, you!'
    
    from string import  punctuation
    
    print(s.translate({ord(k):"" for k in punctuation}).lower())
    hi you
    

    在一个功能:

    from string import punctuation
    
    def remove_punctuation(s):
        return s.translate(None,punctuation).lower()
    
    def remove_punctuation(s):
        return s.translate({ord(k): "" for k in punctuation}).lower()
    

    输出:

    In [3]: remove_punctuation(' No under_score!')
    Out[3]: ' no underscore'
    
    In [4]: remove_punctuation('Hi, you!')
    Out[4]: 'hi you'
    

    如果要删除前导空格,请添加条带 .

    from string import punctuation
    def remove_punctuation(s):
        return s.translate(None,punctuation).lower().strip()
    

    输出:

    In [6]: remove_punctuation(' No under_score!')
    Out[6]: 'no underscore'
    
    In [7]: remove_punctuation('Hi, you!')
    Out[7]: 'hi you'
    
  • 0

    发电机理解怎么样?它比使用RegExp更具可读性 .

    def removePunctuation(s):
        return ''.join(l for l in s if l.isalnum() or l == ' ').lower().strip()
    

    或作为 lambda

    removePunctuation = lambda s: ''.join(l for l in s if l.isalnum() or l == ' ').lower().strip()
    
  • 6

    您可以从其他方面解决问题:

    re.sub('([^\w ]|_)+', '', 'a ,_  b').lower().strip()
    

    它给了 a b

    所以你要说:删除所有非字母数字字符而不是空格或下划线字符 .

相关问题