有没有一种有效的方式在Python中从字符串中去除数字?可以使用nltk或基本的Python方法吗?
谢谢, Ben
有没有一种有效的方式在Python中从字符串中去除数字?可以使用nltk或基本的Python方法吗?
谢谢, Ben
import re
output = re.sub(r'\d+', '', '123hello 456world')
print output # 'hello world'
str.translate
应该是高效的。
In [7]: 'hello467'.translate(None, '0123456789')
Out[7]: 'hello'
为了比较str.translate
和re.sub
:
In [13]: %%timeit r=re.compile(r'\d')
output = r.sub('', my_str)
....:
100000 loops, best of 3: 5.46 µs per loop
In [16]: %%timeit pass
output = my_str.translate(None, '0123456789')
....:
1000000 loops, best of 3: 713 ns per loop
str.translate
有点难以同时兼容2.x/3.x :( - Jon Clementsmy_str.translate({ord(ch): None for ch in '0123456789'})
来实现对字符串中数字的删除。 - Jon Clements'123hello 456world' - x5.0
'1234567890987654321012345678909876543210' - x17.0
'5a$%&^@)9lhk45g08j%Gmj3g09jSDGjg0034k' - x9.0
'hello world im your boss' - x 1.8
- Ross以下是一种使用 str.join()
, str.isnumeric()
和生成器表达式的方法,适用于 3.x 版本:
>>> my_str = '123Hello, World!4567'
>>> output = ''.join(c for c in my_str if not c.isnumeric())
>>> print(output)
Hello, World!
>>>
>>> my_str = u'123Hello, World!4567'
>>> output = ''.join(c for c in my_str if not c.isnumeric())
>>> print(output)
Hello, World!
>>>
嗯。再扔进一根回形针,我们就有了一集《百战天龙》。
我知道这已经被归为重复问题了,但是这里有一个适用于Python 2和Python 3的方法:
>>> my_str = '123Hello, World!4567'
>>> output = ''.join(map(lambda c: '' if c in '0123456789' else c, my_str))
>>> print(output)
Hello, World!
>>>