我需要从字符串中删除所有特殊字符,标点符号和空格,以便我只有字母和数字。
当前回答
对于其他语言,如德语,西班牙语,丹麦语,法语等包含特殊字符(如德语“Umlaute”ü, ä, ö),只需将这些添加到正则表达式搜索字符串:
例如德语:
re.sub('[^A-ZÜÖÄa-z0-9]+', '', mystring)
其他回答
使用翻译:
import string
def clean(instr):
return instr.translate(None, string.punctuation + ' ')
警告:仅适用于ascii字符串。
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'
较短的方法:
import re
cleanString = re.sub('\W+','', string )
如果你想在单词和数字之间有空格,用''代替''
#!/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
你可以添加更多的特殊字符,这将被“意味着什么,即他们将被删除”所取代。
这将删除除空格外的所有非字母数字字符。
string = "Special $#! characters spaces 888323"
''.join(e for e in string if (e.isalnum() or e.isspace()))
特殊字符空格888323
推荐文章
- 即使模板文件存在,Flask也会引发TemplateNotFound错误
- defaultdict的嵌套defaultdict
- 构造tkinter应用程序的最佳方法?
- 如何在Python中逐行打印字典?
- 当试图运行Python脚本时,“ImportError:没有命名模块”
- pylab和pyplot的区别是什么?
- Argparse:确定使用了哪个子解析器
- django导入错误-没有core.management模块
- 在芹菜中检索队列中的任务列表
- 如何从JavaScript中使用正则表达式的字符串中剥离所有标点符号?
- Ruby数组到字符串的转换
- 使用beautifulsoup提取属性值
- 如何禁用标准错误流的日志记录?
- 用Matplotlib在Python中绘制时间
- 正则表达式中的单词边界是什么?