python爬虫程序中能否返回指定数量的匹配记录(re模块)

re.findall()返回的是所有匹配记录

阅读 4.6k
4 个回答
import re
 
p = re.compile(r'\d+')
print p.findall('one1two2three3four4')
print p.findall('one1two2three3four4')[0:2]
 
### output ###
# ['1', '2', '3', '4']
# ['1', '2']

你可以用切片操作返回来处理findall返回的结果来达到你的目的

or

import re                                                          

count = 0
# The end point number
endpoint = 2

p = re.compile(r'\d+')
for m in p.finditer('one1two2three3four4'):
    count += 1
    if count > endpoint: break
    print m.group()
    
### output ###
# 1 2

findall()返回的是一个列表,你需要对其中内容进行一步操作时,例如直接访问或写入数据库的时候,遍厉列表时用一个变量限制一下就行了。

还是我理解错了你的意思?

len()一下,知道长度了就能制定数量了。我理解的对吗?

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题