3

该方法是否有与 BeautifulSoup 的limit=X参数等效的正则表达式findall?我的意思是,如何找到有问题的前 X 个单词然后中断代码执行?谢谢你

4

2 回答 2

4

使用re.finditeritertools.islice

from itertools import islice
import re

limit = 2

for x in islice(re.finditer(r'\d+', '1 2 33'), limit):
    print(x.group())

作为一个函数:

def findall_limiter(pattern, string, flags=0):
    return islice(re.finditer(pattern, string, flags), limit)

例如。

for match in findall_limiter(r'\d+', '1 2 33', 2):
    # do stuff
于 2013-04-26T11:57:17.990 回答
3

您可以使用re.finditer它返回一个迭代器,而不是一次生成所有值:

In [21]: strs="12345678"

In [22]: it=re.finditer("\d",strs)

In [23]: [next(it).group(0) for _ in xrange(4)] #returns only 4 mathces
Out[23]: ['1', '2', '3', '4']

尽管StopIteration当限制大于匹配数时这可能会引发错误。一个简单的解决方法是使用异常处理或使用itertools.isclice

In [26]: def limiter(strs,pattern,limit):
    it=re.finditer(pattern,strs)
    try:
        for _ in xrange(limit):
            yield next(it).group(0)
    except StopIteration:        
        pass
   ....:     

In [27]: list(limiter("12345","\d",3))
Out[27]: ['1', '2', '3']

In [28]: list(limiter("12345","\d",6))
Out[28]: ['1', '2', '3', '4', '5']

In [29]: list(limiter("12345","\d",10))
Out[29]: ['1', '2', '3', '4', '5']

帮助re.finditer

In [24]: re.finditer?
Type:       function
String Form:<function finditer at 0xb74114c4>
File:       /usr/lib/python2.7/re.py
Definition: re.finditer(pattern, string, flags=0)
Docstring:
Return an iterator over all non-overlapping matches in the
string.  For each match, the iterator returns a match object.

Empty matches are included in the result.
于 2013-04-26T11:56:08.560 回答