python爬虫程序中能否返回指定数量的匹配记录(re模块)
阿神
阿神 2017-04-17 16:52:42
[Python讨论组]
阿神
阿神

闭关修行中......

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

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

ringa_lee

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

巴扎黑

try beautifulSoup
http://www.crummy.com/software/BeautifulSoup/bs4/doc/index.zh.html#find

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号