从字符串中删除所有特殊字符、标点符号和空格
- 2025-01-21 09:01:00
- admin 原创
- 133
问题描述:
我需要从字符串中删除所有特殊字符、标点和空格,以便只保留字母和数字。
解决方案 1:
无需正则表达式即可完成此操作:
>>> string = "Special $#! characters spaces 888323"
>>> ''.join(e for e in string if e.isalnum())
'Specialcharactersspaces888323'
您可以使用str.isalnum
:
S.isalnum() -> bool Return True if all characters in S are alphanumeric and there is at least one character in S, False otherwise.
如果您坚持使用正则表达式,其他解决方案也可以。但请注意,如果可以在不使用正则表达式的情况下完成,那么这是最好的方法。
解决方案 2:
这是一个正则表达式,用于匹配非字母或数字的字符串:
[^A-Za-z0-9]+
以下是执行正则表达式替换的 Python 命令:
re.sub('[^A-Za-z0-9]+', '', mystring)
解决方案 3:
更短的方法:
import re
cleanString = re.sub('W+','', string )
如果希望单词和数字之间有空格,请将 '' 替换为 ' '
解决方案 4:
结论
我对提供的答案进行了计时。
import re
re.sub('W+','', string)
通常比下一个最快的最佳答案快 3 倍。
使用此选项时应小心谨慎。某些特殊字符(例如ø)可能无法使用此方法进行条纹处理。
看到这个之后,我有兴趣通过找出哪个答案在最短的时间内执行来扩展所提供的答案,因此我仔细检查了一些建议的答案,并根据timeit
两个示例字符串进行了检查:
string1 = 'Special $#! characters spaces 888323'
string2 = 'how much for the maple syrup? $20.99? That s ridiculous!!!'
示例 1
'.join(e for e in string if e.isalnum())
string1
- 结果:10.7061979771string2
- 结果:7.78372597694
示例 2
import re
re.sub('[^A-Za-z0-9]+', '', string)
string1
- 结果:7.10785102844string2
- 结果:4.12814903259
示例 3
import re
re.sub('W+','', string)
string1
- 结果:3.11899876595string2
- 结果:2.78014397621
上述结果是以下平均值中最低返回结果的乘积:repeat(3, 2000000)
示例 3比示例 1快 3 倍。
解决方案 5:
Python 2.*
我认为filter(str.isalnum, string)
有效
In [20]: filter(str.isalnum, 'string with special chars like !,#$% etcs.')
Out[20]: 'stringwithspecialcharslikeetcs'
Python 3.*
在 Python3 中,filter( )
函数将返回一个可迭代对象(而不是像上面那样的字符串)。必须重新连接才能从可迭代对象中获取字符串:
''.join(filter(str.isalnum, string))
或者传入list
join 使用(不确定,但可以快一点)
''.join([*filter(str.isalnum, string)])
注意:[*args]
从Python >= 3.5开始解包有效
解决方案 6:
#!/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
您可以添加更多特殊字符,这些字符将被“”替换,这意味着什么都没有,即它们将被删除。
解决方案 7:
string.punctuation 包含以下字符:
'!"#$%&\'()*+,-./:;<=>?@[\]^_`{|}~'
您可以使用translate和maketrans函数将标点符号映射到空值(替换)
import string
'This, is. A test!'.translate(str.maketrans('', '', string.punctuation))
输出:
'This is A test'
解决方案 8:
与其他人使用正则表达式的方式不同,我会尝试排除每个不想要的字符,而不是明确列举我不想要的字符。
例如,如果我只想要从“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())
解决方案 9:
s = re.sub(r"[-()\"#/@;:<>{}`+=~|.!?,]", "", s)
解决方案 10:
假设您想使用正则表达式,并且您想要/需要支持 2to3 的 Unicode 识别 2.x 代码:
>>> import re
>>> rx = re.compile(u'[W_]+', re.UNICODE)
>>> data = u''.join(unichr(i) for i in range(256))
>>> rx.sub(u'', data)
u'0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzxaaxb2 [snip] xfexff'
>>>
解决方案 11:
最通用的方法是使用 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 以查找所有相关类别。当然,您也可以按标点符号类别进行筛选。
解决方案 12:
对于包含特殊字符(如德语“Umlaute”为ü
, ä
, ö
)的其他语言(例如德语、西班牙语、丹麦语、法语等),只需将这些字符添加到正则表达式搜索字符串中:
德语示例:
re.sub('[^A-ZÜÖÄa-z0-9]+', '', mystring)
解决方案 13:
这将从字符串中删除所有特殊字符、标点符号和空格,只保留数字和字母。
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)
解决方案 14:
使用翻译:
import string
def clean(instr):
return instr.translate(None, string.punctuation + ' ')
警告:仅适用于 ascii 字符串。
解决方案 15:
这将删除除空格之外的所有非字母数字字符。
string = "Special $#! characters spaces 888323"
''.join(e for e in string if (e.isalnum() or e.isspace()))
特殊字符 空格 888323
解决方案 16:
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"", i)
count += 1
print("The count of Python : ", text.count("python"))
解决方案 17:
十年后,我在下面写下了最好的解决方案。您可以从字符串中删除/清除所有特殊字符、标点符号、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'
解决方案 18:
function regexFuntion(st) {
const regx = /[^ws]/gi; // allow : [a-zA-Z0-9, space]
st = st.replace(regx, ''); // remove all data without [a-zA-Z0-9, space]
st = st.replace(/ss+/g, ' '); // remove multiple space
return st;
}
console.log(regexFuntion('$Hello; # -world--78asdf+-===asdflkj******lkjasdfj67;'));
// Output: Hello world78asdfasdflkjlkjasdfj67
解决方案 19:
import re
abc = "askhnl#$%askdjalsdk"
ddd = abc.replace("#$%","")
print (ddd)
您将看到结果如下
'阿斯肯拉斯克贾尔斯德克
扫码咨询,免费领取项目管理大礼包!