我需要从字符串中删除所有特殊字符,标点符号和空格,以便我只有字母和数字。
当前回答
最通用的方法是使用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。当然你也可以过滤 按标点符号分类。
其他回答
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
这将删除除空格外的所有非字母数字字符。
string = "Special $#! characters spaces 888323"
''.join(e for e in string if (e.isalnum() or e.isspace()))
特殊字符空格888323
下面是一个正则表达式,用于匹配不是字母或数字的字符串:
[^A-Za-z0-9]+
下面是执行正则表达式替换的Python命令:
re.sub('[^A-Za-z0-9]+', '', mystring)
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"))
最通用的方法是使用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。当然你也可以过滤 按标点符号分类。
推荐文章
- 即使模板文件存在,Flask也会引发TemplateNotFound错误
- defaultdict的嵌套defaultdict
- 构造tkinter应用程序的最佳方法?
- 如何在Python中逐行打印字典?
- 当试图运行Python脚本时,“ImportError:没有命名模块”
- pylab和pyplot的区别是什么?
- Argparse:确定使用了哪个子解析器
- django导入错误-没有core.management模块
- 在芹菜中检索队列中的任务列表
- 如何从JavaScript中使用正则表达式的字符串中剥离所有标点符号?
- Ruby数组到字符串的转换
- 使用beautifulsoup提取属性值
- 如何禁用标准错误流的日志记录?
- 用Matplotlib在Python中绘制时间
- 正则表达式中的单词边界是什么?