[英]remove all special characters, punctuation from string and limit it to first 200 characters
您好,In需要刪除字符串中的所有特殊字符,標點符號和空格,以便我只有字母和數字。 最終字符串的長度應僅為前200個字符。
我知道一個解決方案是:
string = "Special $#! character's spaces 888323"
string = ''.join(e for e in string if e.isalnum())[:200]
但這將首先刪除所有不需要的字符,然后對其進行切片。 是否有可以像生成器那樣工作的東西,即,一旦總字符數為200,它就會崩潰。 我想要一個pythonic解決方案。 PS:我知道我可以通過FOR循環來實現。
from itertools import islice
"".join(islice((e for e in string if e.isalnum()), 200))
但就我個人而言,我認為for循環對我來說聽起來要好得多。
將生成器表達式或函數與itertools.islice
:
from itertools import islice
s = "Special $#! character's spaces 888323"
gen = (e for e in s if e.isalnum())
new_s = ''.join(islice(gen, 200))
請注意,如果字符串不是很大,並且數字n
(此處為200)與字符串長度相比不小,則應使用str.translate
進行簡單切片,因為與基於Python的for循環相比,它將非常快:
>>> from string import whitespace, punctuation
>>> s.translate(None, whitespace+punctuation)[:10]
'Specialcha'
大字符串的一些時間比較:
>>> s = "Special $#! character's spaces 888323" * 10000
>>> len(s)
390000
# For very small n
>>> %timeit ''.join(islice((e for e in s if e.isalnum()), 200))
10000 loops, best of 3: 20.2 µs per loop
>>> %timeit s.translate(None, whitespace+punctuation)[:200]
1000 loops, best of 3: 383 µs per loop
# For mid-sized n
>>> %timeit ''.join(islice((e for e in s if e.isalnum()), 10000))
1000 loops, best of 3: 930 µs per loop
>>> %timeit s.translate(None, whitespace+punctuation)[:10000]
1000 loops, best of 3: 378 µs per loop
# When n is comparable to length of string.
>>> %timeit ''.join(islice((e for e in s if e.isalnum()), 100000))
100 loops, best of 3: 9.41 ms per loop
>>> %timeit s.translate(None, whitespace+punctuation)[:100000]
1000 loops, best of 3: 385 µs per loop
如果正則表達式不能解決您的問題,則可能只是您尚未使用足夠的正則表達式:-)這是一種單行代碼(可對導入進行折價),將其限制為20個字符(因為您的測試數據沒有)不符合您的規格):
>>> import re
>>> string = "Special $#! character's spaces 888323"
>>> re.sub("[^A-Za-z0-9]","",string)[:20]
'Specialcharactersspa'
雖然從技術上講不是生成器,但只要您不必處理真正的大量字符串,它就可以正常工作。
它的作用是避免了分裂,並在原來的解決方案歸隊:
''.join(e for e in something)
毫無疑問,正則表達式處理會產生一些成本,但是我很難相信它與建立一個臨時列表然后再將其拆成字符串一樣高。 不過,如果您擔心的話,應該測量而不是猜測!
如果您想要一個實際的生成器,則很容易實現一個生成器:
class alphanum(object):
def __init__(self, s, n):
self.s = s
self.n = n
self.ix = 0
def __iter__(self):
return self
def __next__(self):
return self.next()
def next(self):
if self.n <= 0:
raise StopIteration()
while self.ix < len(self.s) and not self.s[self.ix].isalnum():
self.ix += 1
if self.ix == len(self.s):
raise StopIteration()
self.ix += 1
self.n -= 1
return self.s[self.ix-1]
def remainder(self):
return ''.join([x for x in self])
for x in alphanum("Special $#! chars", 10):
print x
print alphanum("Special $#! chars", 10).remainder()
它顯示了如何將其用作“字符”迭代器以及字符串修飾符:
S
p
e
c
i
a
l
c
h
a
Specialcha
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.