python數(shù)據(jù)分析之將爬取的數(shù)據(jù)保存為csv格式
csv文件
一種用逗號分割來實現(xiàn)存儲表格數(shù)據(jù)的文本文件。
python的csv模塊
python遍歷代碼:
arr = [12, 5, 33, 4, 1]
#遍歷輸出1
for i in range(0, len(arr)):
item = arr[i]
print(item)
#遍歷輸出2
for item in arr:
print(item)
#遍歷輸出3
string_arr = ["hi", "hello", "你好", "aloha"]
for item in string_arr:
print("本次循環(huán) item 變量的值", item)
從csv文件讀取內(nèi)容
用DictReader對象的創(chuàng)建方法以及通過filenames屬性獲取csv表格的表頭。
import csv
#打開csv
fo = open("info.csv")
#打開csv文件的文件對象作為參數(shù)來創(chuàng)建dictreader類的對象,存在reader變量中
reader = csv.DictReader(fo)
#調(diào)用reader對象的filednames屬性,獲取csv文件表格的開頭
headers = reader.fieldnames
#關(guān)閉文件
fo.close()
#打印
print(headers)
獲取表格實際內(nèi)容。
fo = open("info.csv")
reader = csv.DictReader(fo)
#創(chuàng)建列表,存儲讀到的行
row_list = []
#遍歷
for row in reader:
row_list.append(row)
fo.close()
#打印
print(row_list[0])
#遍歷row_list
for d in row_list:
#d是字典,直接打印key為年齡值即可
print(d["年齡"])
#打印
寫入csv文件
python提供了DictWriter方法,可以講表格數(shù)據(jù)以字典的形式存儲到csv文件中。
import csv
#打開一個文件,假設(shè)是info.csv,寫入所以是w
#newline='',寫入時需要指定
fo = open("info2.csv", "w", newline='')
#將表頭存儲到一個列表里
header = ["姓名", "年齡", "部門"]
#創(chuàng)建一個DictWriter對象,第二個參數(shù)就是上面創(chuàng)建的表頭
writer = csv.DictWriter(fo, header)
writer.writeheader()
#寫入一行記錄,以字典的形式,key需要與表頭對應(yīng)
writer.writerow({"姓名": "小明", "年齡":"28", "部門": "行政部"})
#關(guān)閉文件
fo.close()
運行后,相應(yīng)的文件夾下會出現(xiàn)一個對應(yīng)的csv文件。

也可以使用writer.writerows(row_list)來寫入多個。
運用實例
數(shù)據(jù)準(zhǔn)備
1、打開網(wǎng)頁,讀取內(nèi)容,并創(chuàng)建相應(yīng)的BeautifulSoup對象
2、找到包含新聞的div元素列表
3、從2中抽取標(biāo)題
4、從2中抽取時間
from bs4 import BeautifulSoup
def create_doc_from_filename(filename):
fo = open(filename, "r", encoding='utf-8')
html_content = fo.read()
fo.close
doc = BeautifulSoup(html_content)
return doc
(記得要pip install bs4)
#輸入?yún)?shù)是BeautifulSoup對象,返回包含新聞的div元素列表
def find_index_labels(doc):
index_labels = doc.find_all("div", class_ = "indexs")
return index_labels
#實現(xiàn)新聞標(biāo)題的抽取函數(shù)
def get_title(label_object):
#從剛才的參數(shù)傳入的標(biāo)簽對象中過濾出所有的target = _blank的a標(biāo)簽
a_labels = label_object.find_all("a", target = "_blank")
#取得第一個標(biāo)簽對象
my_label = a_labels[0]
#將標(biāo)簽的文字內(nèi)容作為返回值返回
return my_label.get_text()
#實現(xiàn)獲取新聞發(fā)布時間的函數(shù)
def get_pub_time(label_object):
#找到class = comment-link的span標(biāo)簽
spans = label_object.find_all("span", class_ = "comment-link")
#取第一個
span = spans[0]
#返回標(biāo)題屬性
return span["title"]
#獲取新聞標(biāo)題與列表
#調(diào)用create_doc_from_filename函數(shù)
doc = create_doc_from_filename("jiandan.html")
#傳入BeautifulSoup對象,將返回的div列表存儲在index_labels中
index_labels = find_index_labels(doc)
for label_object in index_labels:
title = get_title(label_object)
pub_time = get_pub_time(label_object)
print("標(biāo)題", title)
print("發(fā)布時間", pub_time)

將數(shù)據(jù)存為字典的形式
#獲取新聞標(biāo)題與列表
#調(diào)用create_doc_from_filename函數(shù)
doc = create_doc_from_filename("jiandan.html")
#傳入BeautifulSoup對象,將返回的div列表存儲在index_labels中
index_labels = find_index_labels(doc)
news_dict_list = []
for label_object in index_labels:
title = get_title(label_object)
pub_time = get_pub_time(label_object)
news = {"標(biāo)題": title, "發(fā)布時間": pub_time}
news_dict_list.append(news)
print(news_dict_list)

存儲到csv文件
#創(chuàng)建csv
fo = open("news.csv", "w", newline='', encoding='utf-8')
#表頭
header = ["標(biāo)題", "發(fā)布時間"]
writer = csv.DictWriter(fo, header)
#寫入表頭
writer.writeheader()
#將上一步的字典寫入csv文件中
writer.writerows(news_dict_list)
fo.close()

總結(jié)
到此這篇關(guān)于python數(shù)據(jù)分析之將爬取的數(shù)據(jù)保存為csv格式的文章就介紹到這了,更多相關(guān)python爬取數(shù)據(jù)保存csv格式內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
python使用numpy中的size()函數(shù)實例用法詳解
在本篇文章里小編給整理的是一篇關(guān)于python使用numpy中的size()函數(shù)實例用法詳解內(nèi)容,有興趣的朋友們可以學(xué)習(xí)下。2021-01-01
python中matplotlib條件背景顏色的實現(xiàn)
這篇文章主要給大家介紹了關(guān)于python中matplotlib條件背景顏色的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家學(xué)習(xí)或者使用python具有一定的參考學(xué)習(xí)價值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧2019-09-09
Python使用multiprocessing如何實現(xiàn)多進(jìn)程
這篇文章主要介紹了Python使用multiprocessing如何實現(xiàn)多進(jìn)程問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-02-02
python將三維數(shù)組展開成二維數(shù)組的實現(xiàn)
今天小編就為大家分享一篇python將三維數(shù)組展開成二維數(shù)組的實現(xiàn),具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-11-11
詳解利用django中間件django.middleware.csrf.CsrfViewMiddleware防止csrf
這篇文章主要介紹了詳解利用django中間件django.middleware.csrf.CsrfViewMiddleware防止csrf攻擊,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-10-10
基于tensorflow for循環(huán) while循環(huán)案例
這篇文章主要介紹了基于tensorflow for循環(huán) while循環(huán)案例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-06-06
使用 Python 合并多個格式一致的 Excel 文件(推薦)
這篇文章主要介紹了使用 Python 合并多個格式一致的 Excel 文件,本文給大家介紹的非常詳細(xì),具有一定的參考借鑒價值,需要的朋友可以參考下2019-12-12

