python - for循環(huán)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)’’’輸出百度搜索結(jié)果數(shù)據(jù):當(dāng)前關(guān)鍵詞,排名,排名網(wǎng)站,百度url(需轉(zhuǎn)義后才是真實的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://www.leifengta.com.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出正確結(jié)果,但是我希望能生成csv報表文件,嘗試修改for為函數(shù)失敗。小菜鳥一枚,不知道怎么搞了,求大神指點
問題解答
回答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)’’’輸出百度搜索結(jié)果數(shù)據(jù):當(dāng)前關(guān)鍵詞,排名,排名網(wǎng)站,百度url(需轉(zhuǎn)義后才是真實的url),標題’’’# 保存標題result_csv_writer.writerow([’關(guān)鍵詞’, ’排名’, ’排名網(wǎng)站’, ’百度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://www.leifengta.com.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()
代碼未測試,有問題請簡單修改
相關(guān)文章:
1. 運行python程序時出現(xiàn)“應(yīng)用程序發(fā)生異常”的內(nèi)存錯誤?2. 利用IPMI遠程安裝centos報錯!3. html5和Flash對抗是什么情況?4. javascript - QQ第三方登錄的問題5. 在mac下出現(xiàn)了兩個docker環(huán)境6. node.js - mongodb查找子對象的名稱為某個值的對象的方法7. 測試自動化html元素選擇器元素ID或DataAttribute [關(guān)閉]8. spring-mvc - spring-session-redis HttpSessionListener失效9. java - Spring boot 讀取 放在 jar 包外的,log4j 配置文件,系統(tǒng)有創(chuàng)建日志文件,不寫入日志信息。10. 淺談Vue使用Cascader級聯(lián)選擇器數(shù)據(jù)回顯中的坑

網(wǎng)公網(wǎng)安備