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


当前回答

较短的方法:

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

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

其他回答

import re
my_string = """Strings are amongst the most popular data types in Python. We can create the strings by enclosing characters in quotes. Python treats single quotes the 

和双引号一样。”""

# if we need to count the word python that ends with or without ',' or '.' at end

count = 0
for i in text:
    if i.endswith("."):
        text[count] = re.sub("^([a-z]+)(.)?$", r"\1", i)
    count += 1
print("The count of Python : ", text.count("python"))

下面是一个正则表达式,用于匹配不是字母或数字的字符串:

[^A-Za-z0-9]+

下面是执行正则表达式替换的Python命令:

re.sub('[^A-Za-z0-9]+', '', mystring)

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'

这可以不使用regex完成:

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

你可以使用str.isalnum:

S.isalnum() -> bool 如果S中的所有字符都是字母数字,则返回True 且S中至少有一个字符,否则为假。

如果坚持使用正则表达式,其他解决方案也可以。但是请注意,如果可以在不使用正则表达式的情况下完成,那么这是最好的方法。

Python 2 . *

我认为只要filter(str。Isalnum,字符串)工作

In [20]: filter(str.isalnum, 'string with special chars like !,#$% etcs.')
Out[20]: 'stringwithspecialcharslikeetcs'

Python 3。*

在Python3中,filter()函数将返回一个可迭代对象(而不是与上面不同的字符串)。从itertable中获取字符串必须返回连接:

''.join(filter(str.isalnum, string)) 

或者在连接中传递列表(不确定,但可以快一点)

''.join([*filter(str.isalnum, string)])

注意:unpacking in [*args] valid from Python >= 3.5