日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

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

發布時間:2025/3/8 python 18 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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

總結

以上是生活随笔為你收集整理的python 函数中所有print保存csv_python for循环print怎样才能输出csv呢的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。