python - for循環print怎樣才能輸出csv呢
問題描述
import csv,redef search(req,line): text = re.search(req,line) if text:data = text.group(1) else:data = ’no’ return datacsvfile = 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’<span class='g'>(.*?)/.*</span>’,html) bdurl = search(r’href='http://m.propowerdrill.cn/wenda/(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為函數失敗。小菜鳥一枚,不知道怎么搞了,求大神指點
問題解答
回答1:可以這樣
import csv,redef search(req,line): text = re.search(req,line) if text:data = text.group(1) else:data = ’no’ return datareuslts = []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’<span class='g'>(.*?)/.*</span>’,html) bdurl = search(r’href='http://m.propowerdrill.cn/wenda/(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()
代碼未測試,有問題請簡單修改
相關文章:
1. node.js - nodejs+express+vue2. javascript - vue2.0中使用vue2-dropzone的demo,vue2-dropzone的github網址是什么??百度不到。3. java軟引用在android中有實際應用場景嗎?4. javascript - JS如何取對稱范圍的隨機數?5. 前端 - @media query 使用出現的問題?6. Python 子類能否覆蓋全局函數?7. node.js - win7下,npm 無法下載依賴包,淘寶鏡像也裝不上,求幫忙???8. mysql - sql 找出2個數據庫的差異表名9. elasticsearch - Elastisearch怎么求查詢結果的交集,如MYSQL的interset10. vue計算屬性怎么樣與for結合使用
