我需要从字符串中删除所有特殊字符,标点符号和空格,以便我只有字母和数字。
当前回答
#!/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
你可以添加更多的特殊字符,这将被“意味着什么,即他们将被删除”所取代。
其他回答
最通用的方法是使用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。当然你也可以过滤 按标点符号分类。
字符串。标点符号包含以下字符:
'!"#$%&\'()*+,-./:;<=>?@[\]^_`{|}~'
可以使用translate和maketrans函数将标点符号映射为空值(替换)
import string
'This, is. A test!'.translate(str.maketrans('', '', string.punctuation))
输出:
'This is A test'
与使用正则表达式的其他人不同,我将尝试排除不是我想要的每个字符,而不是显式地列举我不想要的字符。
例如,如果我只想要字符从'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())
这将删除除空格外的所有非字母数字字符。
string = "Special $#! characters spaces 888323"
''.join(e for e in string if (e.isalnum() or e.isspace()))
特殊字符空格888323
假设你想要使用正则表达式并且你想要/需要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'
>>>
推荐文章
- 证书验证失败:无法获得本地颁发者证书
- 当使用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