簡體   English   中英

使用python中的re.sub函數刪除字符串中的特殊字符和撇號以及多余的空格

[英]Remove special character and apostrophe and unwanted space in string using re.sub function in python

import re
def removePunctuation(text):

    return re.sub(r'[ \W,_,]+', ' ', text.lower()).lstrip()
print removePunctuation('Hi, 'you!')
print removePunctuation(' No's under_score!')

我想要結果:

hi you
nos under score 

你可以試試看

def removePunctuation(text):
    return re.sub(r'^\s+|\s+$|[^A-Za-z\d\s]', '', text.lower())

要么

似乎您想用空格替換所有下划線,並用空字符串替換所有其他特殊字符。

>>> re.sub(r'^\s+|\s+$|[^A-Za-z\d\s]', '', " No's under_score!".lower().replace('_', ' '))
'nos under score'
>>> re.sub(r'^\s+|\s+$|[^A-Za-z\d\s]', '', " Hi, 'you!'".lower().replace('_', ' '))
'hi you'

正則表達式是一個很棒的字符串處理工具,但是在python中有時它可能是一個過大的殺傷力,這個特定示例就是其中的一種。 Python對經過精心設計的字符串庫進行了一些思考,這些字符串庫無需使用正則表達式就可以實現奇跡,對於本示例,str.translate和unicode.translate是理想的選擇

對於Python 2.X

def removePunctuation(text):
    from string import punctuation
    return ' '.join(text.translate(None, punctuation))

對於Unicode和Python 3.X

def removePunctuationU(text):
    from string import punctuation
    return u' '.join(text.translate({ord(c): None for c in punctuation}).split())

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM