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.baoyu77737.com/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.baoyu77737.com/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. mysql - ubuntu開啟3306端口失敗,有什么辦法可以解決?2. typeof是啥意思3. java - NamedParameterJdbcTemplate 性能測試4. java - 如何讓maven優先使用用戶setting.xml的配置?5. 這是什么情況???6. javascript - 這是什么插件能把能把cli里面的webpack打包信息格式化?7. javascript - h5頁面中特殊字符在某些安卓手機上亂碼(__??_-?? -----> __?-??)8. java - android 有沒有離線版的sdk文檔 不用聯網就可以本地查找的,提高查閱文檔的速度?9. Python的os.listdir在獲取文件列表時的順序問題10. windows-7 - Win7中Vmware Workstatoin與Xampp中Apache服務器端口沖突?
