过滤掉只包含数字和/或标点符号的字符串 - python

时间:2014-02-11 08:27:41

标签: python string digit punctuation

我只需要过滤掉只包含数字和/或一组标点符号的字符串。

我已经尝试检查每个字符,然后对布尔条件求和以检查它是否等于len(str)。是否有更多的pythonic方法来做到这一点:

>>> import string
>>> x = ['12,523', '3.46', "this is not", "foo bar 42", "23fa"]
>>> [i for i in x if [True if j.isdigit() else False for j in i] ]
['12,523', '3.46', 'this is not', 'foo bar 42']
>>> [i for i in x if sum([True if j.isdigit() or j in string.punctuation else False for j in i]) == len(i)]
['12,523', '3.46']

2 个答案:

答案 0 :(得分:8)

all与生成器表达式一起使用,您无需计算,比较长度:

>>> [i for i in x if all(j.isdigit() or j in string.punctuation for j in i)]
['12,523', '3.46']

BTW,上面和OP的代码将包含仅包含标点符号的字符串。

>>> x = [',,,', '...', '123', 'not number']
>>> [i for i in x if all(j.isdigit() or j in string.punctuation for j in i)]
[',,,', '...', '123']

要处理此问题,请添加更多条件:

>>> [i for i in x if all(j.isdigit() or j in string.punctuation for j in i) and any(j.isdigit() for j in i)]
['123']

通过将string.punctuation的结果存储在一个集合中,可以使它更快一些。

>>> puncs = set(string.punctuation)
>>> [i for i in x if all(j.isdigit() or j in puncs for j in i) and any(j.isdigit() for j in i)]
['123']

答案 1 :(得分:3)

您可以使用预编译的正则表达式来检查它。

import re, string
pattern = re.compile("[\d{}]+$".format(re.escape(string.punctuation)))
x = ['12,523', '3.46', "this is not", "foo bar 42", "23fa"]
print [item for item in x if pattern.match(item)]

<强>输出

['12,523', '3.46']

@fattru的解决方案和我的

之间的一点时间比较
import re, string
punct = string.punctuation
pattern = re.compile("[\d{}]+$".format(re.escape(string.punctuation)))
x = ['12,523', '3.46', "this is not", "foo bar 42", "23fa"]

from timeit import timeit
print timeit("[item for item in x if pattern.match(item)]", "from __main__ import pattern, x")
print timeit("[i for i in x if all(j.isdigit() or j in punct for j in i)]", "from __main__ import x, punct")

我机器上的输出

2.03506183624
4.28856396675

因此,预编译的RegEx方法的速度是allany方法的两倍。