我想使用python re模块来过滤数字数字的整型数字。
1
700
76093
71365
35837
75671
^^
||--------------------- this position should not be 6,7,8,9,0
|---------------------- this position should not be 5,6,7代码:
int_list=[1,700,76093,71365,35837,75671]
str_list = [str(x).zfill(5) for x in int_list]
reexp = r"\d[0-4,8-9][1-5]\d\d"
import re
p = re.compile(reexp)
result = [int("".join(str(y) for y in x)) for x in str_list if p.match(x)]我有两个问题:
1.是否可以从以下代码生成reexp字符串:
thousand_position = set([1,2,3,4,5,1,1,1,1,1,1,1,1,1,1])
hundred_position = set([1,2,3,4,8,9,0,1,2,3,2,3,1,2])2.如何使reexp更简单,避免小于0前缀的bug?
00700
00500 <--- this will also drops into the reexp, it is a
bug because it has no kilo number
10700
reexp = r"\d[0-4,8-9][1-5]\d\d"耽误您时间,实在对不起
B.Rgs
PS:感谢你对下面的数学解决方案的建议,我知道这可能是简单和快速的,但我希望基于re的版本来平衡其他想法。
发布于 2011-03-24 13:06:04
好的,首先,我将发布一些代码,这些代码实际上执行了您最初描述的操作:
>>> int_list=[1, 700, 76093, 71365, 35837, 75671]
>>> str_list = [str(i).zfill(5) for i in int_list]
>>> filtered = [s for s in str_list if re.match('\d[0-4,8-9][1-5]\d\d', s)]
>>> filtered
['71365']编辑:好的,我想我现在理解你的问题了。您可以使用rjust代替zfill,它将插入空格而不是零。
>>> int_list=[1,700,76093,71365,35837,75671,500]
>>> str_list = [str(i).rjust(5) for i in int_list]
>>> re_str = '\d' + str(list(set([0, 1, 3, 4, 8, 9]))) + str(list(set([1, 2, 3, 4, 5]))) + '\d\d'
>>> filtered = [s for s in str_list if re.match(re_str, s)]
>>> filtered
['71365']我认为用数学的方法来做这件事最终会更快,但也许你有理由使用正则表达式。
发布于 2011-03-24 12:26:28
您确定要使用re模块吗?你可以通过一些简单的数学运算得到你想要做的事情。
def valid_number(n):
return 0 < n%1000/100 < 6 and not 5 >= n%10000/1000 >= 7
int_list = [1,700,76093,71365,35837,75671,]
result = [x for x in int_list if valid_number(x)]或者:
result = filter(valid_number, int_list)https://stackoverflow.com/questions/5414705
复制相似问题