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


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

[^A-Za-z0-9]+

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

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

这可以不使用regex完成:

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

你可以使用str.isalnum:

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

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


最通用的方法是使用unicodedata表的“类别”,它对每个字符进行分类。例如,下面的代码只过滤基于类别的可打印字符:

import unicodedata
# strip of crap characters (based on the Unicode database
# categorization:
# http://www.sql-und-xml.de/unicode-database/#kategorien

PRINTABLE = set(('Lu', 'Ll', 'Nd', 'Zs'))

def filter_non_printable(s):
    result = []
    ws_last = False
    for c in s:
        c = unicodedata.category(c) in PRINTABLE and c or u'#'
        result.append(c)
    return u''.join(result).replace(u'#', u' ')

查看上面给出的所有相关类别的URL。当然你也可以过滤 按标点符号分类。


假设你想要使用正则表达式并且你想要/需要unicode - cognant 2。X代码是2to3-ready:

>>> import re
>>> rx = re.compile(u'[\W_]+', re.UNICODE)
>>> data = u''.join(unichr(i) for i in range(256))
>>> rx.sub(u'', data)
u'0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\xaa\xb2 [snip] \xfe\xff'
>>>

#!/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

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


较短的方法:

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

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


import re
abc = "askhnl#$%askdjalsdk"
ddd = abc.replace("#$%","")
print (ddd)

你会看到你的结果是

'Askhnlaskdjalsdk


使用翻译:

import string

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

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


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


TLDR

我计算了提供的答案。

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

通常比上一个最快的答案快3倍。

使用此选项时应谨慎。一些特殊字符(如ø)不能使用这种方法进行条纹。


在看到这个之后,我有兴趣通过找出在最少的时间内执行的答案来扩展提供的答案,所以我通过timeit检查了一些建议的答案,并对照两个示例字符串:

string1 = '特殊$#!字符空格888323' '枫糖浆多少钱? '20.99美元吗?这太荒谬了!!”

示例1

'.join(e for e in string if e.isalnum())

string1 - Result: 10.7061979771 string2 - Result: 7.78372597694

示例2

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

string1 - Result: 7.10785102844 string2 - Result: 4.12814903259

示例3

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

string1 - Result: 3.11899876595 string2 - Result: 2.78014397621

以上结果是由以下平均值的最低返回结果的乘积:重复(3,2000000)

例3可以比例1快3倍。


s = re.sub(r"[-()\"#/@;:<>{}`+=~|.!?,]", "", s)

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到z'(大写和小写)和数字,我将排除所有其他:

import re
s = re.sub(r"[^a-zA-Z0-9]","",s)

这意味着“用空字符串替换每个不是数字的字符,或者'a到z'或'a到z'范围内的字符”。

事实上,如果你在正则表达式的第一个位置插入特殊字符^,你将得到否定。

额外提示:如果您还需要将结果小写,您可以使正则表达式更快更简单,只要您现在不会发现任何大写。

import re
s = re.sub(r"[^a-z0-9]","",s.lower())

字符串。标点符号包含以下字符:

'!"#$%&\'()*+,-./:;<=>?@[\]^_`{|}~'

可以使用translate和maketrans函数将标点符号映射为空值(替换)

import string

'This, is. A test!'.translate(str.maketrans('', '', string.punctuation))

输出:

'This is A test'

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

例如德语:

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

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

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

特殊字符空格888323


这将删除字符串中的所有特殊字符、标点符号和空格,只包含数字和字母。

import re

sample_str = "Hel&&lo %% Wo$#rl@d"

# using isalnum()
print("".join(k for k in sample_str if k.isalnum()))


# using regex
op2 = re.sub("[^A-Za-z]", "", sample_str)
print(f"op2 = ", op2)


special_char_list = ["$", "@", "#", "&", "%"]

# using list comprehension
op1 = "".join([k for k in sample_str if k not in special_char_list])
print(f"op1 = ", op1)


# using lambda function
op3 = "".join(filter(lambda x: x not in special_char_list, sample_str))
print(f"op3 = ", op3)

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'

function regexFuntion(st) {
  const regx = /[^\w\s]/gi; // allow : [a-zA-Z0-9, space]
  st = st.replace(regx, ''); // remove all data without [a-zA-Z0-9, space]
  st = st.replace(/\s\s+/g, ' '); // remove multiple space

  return st;
}

console.log(regexFuntion('$Hello; # -world--78asdf+-===asdflkj******lkjasdfj67;'));
// Output: Hello world78asdfasdflkjlkjasdfj67