我需要从字符串中删除所有特殊字符,标点符号和空格,以便我只有字母和数字。
当前回答
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'
其他回答
下面是一个正则表达式,用于匹配不是字母或数字的字符串:
[^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"))
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
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倍。
对于其他语言,如德语,西班牙语,丹麦语,法语等包含特殊字符(如德语“Umlaute”ü, ä, ö),只需将这些添加到正则表达式搜索字符串:
例如德语:
re.sub('[^A-ZÜÖÄa-z0-9]+', '', mystring)
推荐文章
- 证书验证失败:无法获得本地颁发者证书
- 当使用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