python 函数中所有print保存csv_python for循环print怎样才能输出csv呢

import csv,re

def search(req,line):

text = re.search(req,line)

if text:

data = text.group(1)

else:

data = 'no'

return data

csvfile = file('serp_html.csv','rb')

reader = csv.reader(csvfile)

'''输出百度搜索结果数据:当前关键词,排名,排名网站,百度url(需转义后才是真实的url),标题'''

for line in reader:

word = line[0]

html = line[1]

number = search(r'id="(\d+)"',html)

domain = search(r'(.*?)/.*',html)

bdurl = search(r'href="(http://www.baidu.com/link\?url=[^"]*?)"',html)

title = search(r'"title":"([^"]*?)"',html)

print '%s,%s,%s,%s,%s' % (word,number,domain,bdurl,title)

以上是一个继承程序,运行后能print出正确结果,但是我希望能生成csv报表文件,尝试修改for为函数失败。

小菜鸟一枚,不知道怎么搞了,求大神指点

可以这样import csv,re

def search(req,line):

text = re.search(req,line)

if text:

data = text.group(1)

else:

data = 'no'

return data

reuslts = []

result_csv = file('new_file.csv', 'wb')

result_csv_writer = csv.writer(result_csv)

'''输出百度搜索结果数据:当前关键词,排名,排名网站,百度url(需转义后才是真实的url),标题'''

# 保存标题

result_csv_writer.writerow(['关键词', '排名', '排名网站', '百度url', '标题'])

for line in reader:

word = line[0]

html = line[1]

number = search(r'id="(\d+)"',html)

domain = search(r'(.*?)/.*',html)

bdurl = search(r'href="(http://www.baidu.com/link\?url=[^"]*?)"',html)

title = search(r'"title":"([^"]*?)"',html)

reuslts.append((word, number, domain, bdurl, title))

//print '%s,%s,%s,%s,%s' % (word,number,domain,bdurl,title)

# 保存多行

result_csv_writer.writerows(reuslts)

result_csv.close()

代码未测试,有问题请简单修改

玩蛇网文章,转载请注明出处和文章网址:https://www.iplaypy.com/wenda/wd13784.html

相关文章 Recommend

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值