我需要从字符串中删除所有特殊字符,标点符号和空格,以便我只有字母和数字。
当前回答
字符串。标点符号包含以下字符:
'!"#$%&\'()*+,-./:;<=>?@[\]^_`{|}~'
可以使用translate和maketrans函数将标点符号映射为空值(替换)
import string
'This, is. A test!'.translate(str.maketrans('', '', string.punctuation))
输出:
'This is A test'
其他回答
最通用的方法是使用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。当然你也可以过滤 按标点符号分类。
这可以不使用regex完成:
>>> string = "Special $#! characters spaces 888323"
>>> ''.join(e for e in string if e.isalnum())
'Specialcharactersspaces888323'
你可以使用str.isalnum:
S.isalnum() -> bool 如果S中的所有字符都是字母数字,则返回True 且S中至少有一个字符,否则为假。
如果坚持使用正则表达式,其他解决方案也可以。但是请注意,如果可以在不使用正则表达式的情况下完成,那么这是最好的方法。
字符串。标点符号包含以下字符:
'!"#$%&\'()*+,-./:;<=>?@[\]^_`{|}~'
可以使用translate和maketrans函数将标点符号映射为空值(替换)
import string
'This, is. A test!'.translate(str.maketrans('', '', string.punctuation))
输出:
'This is A test'
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倍。
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
推荐文章
- 证书验证失败:无法获得本地颁发者证书
- 当使用pip3安装包时,“Python中的ssl模块不可用”
- 无法切换Python与pyenv
- Python if not == vs if !=
- 如何从scikit-learn决策树中提取决策规则?
- 为什么在Mac OS X v10.9 (Mavericks)的终端中apt-get功能不起作用?
- 将旋转的xtick标签与各自的xtick对齐
- Printf与std::字符串?
- 为什么元组可以包含可变项?
- 如何合并字典的字典?
- 如何创建类属性?
- 不区分大小写的“in”
- 在Python中获取迭代器中的元素个数
- 解析日期字符串并更改格式
- 使用try和。Python中的if