![](/img/trans.png)
[英]remove all special characters, punctuation from string and limit it to first 200 characters
[英]Remove all special characters, punctuation and spaces from string
我需要從字符串中刪除所有特殊字符、標點符號和空格,以便我只有字母和數字。
這可以在沒有正則表達式的情況下完成:
>>> string = "Special $#! characters spaces 888323"
>>> ''.join(e for e in string if e.isalnum())
'Specialcharactersspaces888323'
您可以使用str.isalnum
:
S.isalnum() -> bool Return True if all characters in S are alphanumeric and there is at least one character in S, False otherwise.
如果您堅持使用正則表達式,其他解決方案也可以。 但是請注意,如果不使用正則表達式就可以完成,那是最好的方法 go 關於它。
這是一個正則表達式,用於匹配不是字母或數字的字符串:
[^A-Za-z0-9]+
這是執行正則表達式替換的 Python 命令:
re.sub('[^A-Za-z0-9]+', '', mystring)
較短的方式:
import re
cleanString = re.sub('\W+','', string )
如果您想要單詞和數字之間的空格,請將 '' 替換為 ' '
我為提供的答案計時。
import re
re.sub('\W+','', string)
通常比提供的下一個最快的最佳答案快 3 倍。
使用此選項時應小心。 某些特殊字符(例如ø )可能無法使用此方法進行條帶化。
看到這個之后,我有興趣通過找出哪個執行的時間最短來擴展提供的答案,所以我仔細檢查了一些建議的答案timeit
針對兩個示例字符串:
string1 = 'Special $#! characters spaces 888323'
string2 = 'how much for the maple syrup? $20.99? That s ridiculous!!!'
'.join(e for e in string if e.isalnum())
string1
- 結果:10.7061979771string2
- 結果:7.78372597694import re
re.sub('[^A-Za-z0-9]+', '', string)
string1
- 結果:7.10785102844string2
- 結果:4.12814903259import re
re.sub('\W+','', string)
string1
- 結果:3.11899876595string2
- 結果:2.78014397621 上面的結果是從平均值中返回的最低結果的乘積: repeat(3, 2000000)
示例 3可以比示例 1快 3 倍。
我認為filter(str.isalnum, string)
有效
In [20]: filter(str.isalnum, 'string with special chars like !,#$% etcs.')
Out[20]: 'stringwithspecialcharslikeetcs'
在 Python3 中, filter( )
function 將返回一個可迭代的 object(而不是上面的字符串)。 必須加入回來才能從 itertable 中獲取字符串:
''.join(filter(str.isalnum, string))
或在加入使用中傳遞list
(不確定但可以快一點)
''.join([*filter(str.isalnum, string)])
注意:從Python >= 3.5 開始,在[*args]
中解包有效
#!/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
您可以添加更多特殊字符,將被替換為 '' 意味着什么都沒有,即它們將被刪除。
與使用正則表達式的其他人不同,我會嘗試排除所有不是我想要的字符,而不是明確枚舉我不想要的字符。
例如,如果我只想要從“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.punctuation 包含以下字符:
',"#$%&\'()*+.-:/;?<=>?@[\]^_`{|}~'
您可以使用 translate 和 maketrans 函數將 map 標點符號轉換為空值(替換)
import string
'This, is. A test!'.translate(str.maketrans('', '', string.punctuation))
Output:
'This is A test'
s = re.sub(r"[-()\"#/@;:<>{}`+=~|.!?,]", "", s)
假設您想使用正則表達式並且您想要/需要 Unicode-cognisant 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'
>>>
最通用的方法是使用 unicodedata.table 的“類別”,它對每個字符進行分類。 例如,以下代碼僅根據類別過濾可打印字符:
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 以了解所有相關類別。 您當然也可以按標點符號類別進行過濾。
對於其他包含特殊字符的語言,如德語、西班牙語、丹麥語、法語等(如德語“Umlaute”如ü
、 ä
、 ö
),只需將這些添加到正則表達式搜索字符串中:
德語示例:
re.sub('[^A-ZÜÖÄa-z0-9]+', '', mystring)
這將從字符串中刪除所有特殊字符、標點符號和空格,只包含數字和字母。
import re
sample_str = "Hel&&lo %% Wo$#rl@d"
# using isalnum()
print("".join(k for k in sample_str if k.isalnum()))
# using regex
op2 = re.sub("[^A-Za-z]", "", sample_str)
print(f"op2 = ", op2)
special_char_list = ["$", "@", "#", "&", "%"]
# using list comprehension
op1 = "".join([k for k in sample_str if k not in special_char_list])
print(f"op1 = ", op1)
# using lambda function
op3 = "".join(filter(lambda x: x not in special_char_list, sample_str))
print(f"op3 = ", op3)
使用翻譯:
import string
def clean(instr):
return instr.translate(None, string.punctuation + ' ')
警告:僅適用於 ascii 字符串。
我需要從字符串中刪除所有特殊字符、標點符號和空格,以便我只有字母和數字。
這將刪除除空格之外的所有非字母數字字符。
string = "Special $#! characters spaces 888323"
''.join(e for e in string if (e.isalnum() or e.isspace()))
特殊字符空格 888323
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"))
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'
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
import re
abc = "askhnl#$%askdjalsdk"
ddd = abc.replace("#$%","")
print (ddd)
你會看到你的結果
'askhnlaskdjalsdk
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.