我需要从字符串中删除所有特殊字符,标点符号和空格,以便我只有字母和数字。


当前回答

对于其他语言,如德语,西班牙语,丹麦语,法语等包含特殊字符(如德语“Umlaute”ü, ä, ö),只需将这些添加到正则表达式搜索字符串:

例如德语:

re.sub('[^A-ZÜÖÄa-z0-9]+', '', mystring)

其他回答

使用翻译:

import string

def clean(instr):
    return instr.translate(None, string.punctuation + ' ')

警告:仅适用于ascii字符串。

10年后,下面我写下了最好的解决方案。 您可以从字符串中删除/清除所有特殊字符、标点符号、ASCII字符和空格。

from clean_text import clean

string = 'Special $#! characters   spaces 888323'
new = clean(string,lower=False,no_currency_symbols=True, no_punct = True,replace_with_currency_symbol='')
print(new)
Output ==> 'Special characters spaces 888323'
you can replace space if you want.
update = new.replace(' ','')
print(update)
Output ==> 'Specialcharactersspaces888323'

较短的方法:

import re
cleanString = re.sub('\W+','', string )

如果你想在单词和数字之间有空格,用''代替''

#!/usr/bin/python
import re

strs = "how much for the maple syrup? $20.99? That's ricidulous!!!"
print strs
nstr = re.sub(r'[?|$|.|!]',r'',strs)
print nstr
nestr = re.sub(r'[^a-zA-Z0-9 ]',r'',nstr)
print nestr

你可以添加更多的特殊字符,这将被“意味着什么,即他们将被删除”所取代。

这将删除除空格外的所有非字母数字字符。

string = "Special $#! characters   spaces 888323"
''.join(e for e in string if (e.isalnum() or e.isspace()))

特殊字符空格888323