新聞中心
這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
創(chuàng)新互聯(lián)Python教程:如何保存python程序所生產(chǎn)的數(shù)據(jù)?
保存python程序生產(chǎn)數(shù)據(jù)的方法:

open函數(shù)保存
使用with open()新建對象
寫入數(shù)據(jù)(這里使用的是爬取豆瓣讀書中一本書的豆瓣短評作為例子)
import requests
from lxml import etree
#發(fā)送Request請求
url = 'https://book.douban.com/subject/1054917/comments/'
head = {'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.94 Safari/537.36'}
#解析HTML
r = requests.get(url, headers=head)
s = etree.HTML(r.text)
comments = s.xpath('//div[@class="comment"]/p/text()')
#print(str(comments))#在寫代碼的時候可以將讀取的內(nèi)容打印一下
#保存數(shù)據(jù)open函數(shù)
with open('D:/PythonWorkSpace/TestData/pinglun.txt','w',encoding='utf-8') as f:#使用with open()新建對象f
for i in comments:
print(i)
f.write(i+'\n')#寫入數(shù)據(jù),文件保存在上面指定的目錄,加\n為了換行更方便閱讀這里指的注意的是: open函數(shù)的打開模式
pandas包保存
使用pandas保存數(shù)據(jù)到CSV和Excel:
#導(dǎo)入包import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randn(10,4))#創(chuàng)建隨機值
#print(df.head(2))#查看數(shù)據(jù)框的頭部數(shù)據(jù),默認不寫為前5行,小于5行時全部顯示;也可以自定義查看幾行
print(df.tail())##查看數(shù)據(jù)框的尾部數(shù)據(jù),默認不寫為倒數(shù)5行,小于5行時全部顯示;也可以自定義查看倒數(shù)幾行
df.to_csv('D:/PythonWorkSpace/TestData/PandasNumpy.csv')#存儲到CSV中
#df.to_excel('D:/PythonWorkSpace/TestData/PandasNumpy.xlsx')#存儲到Excel中(需要提前導(dǎo)入庫 pip install openpyxl)實例中保存豆瓣讀書的短評代碼如下:
import requests
from lxml import etree
#發(fā)送Request請求
url = 'https://book.douban.com/subject/1054917/comments/'
head = {'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.94 Safari/537.36'}
#解析HTML
r = requests.get(url, headers=head)
s = etree.HTML(r.text)
comments = s.xpath('//div[@class="comment"]/p/text()')
#print(str(comments))#在寫代碼的時候可以將讀取的內(nèi)容打印一下
'''
#保存數(shù)據(jù)open函數(shù)
with open('D:/PythonWorkSpace/TestData/pinglun.txt','w',encoding='utf-8') as f:#使用with open()新建對象f
for i in comments:
print(i)
f.write(i+'\n')#寫入數(shù)據(jù),文件保存在上面指定的目錄,加\n為了換行更方便閱讀
'''
#保存數(shù)據(jù)pandas函數(shù) 到CSV 和Excel
import pandas as pd
df = pd.DataFrame(comments)
#print(df.head())#head()默認為前5行
df.to_csv('D:/PythonWorkSpace/TestData/PandasNumpyCSV.csv')
#df.to_excel('D:/PythonWorkSpace/TestData/PandasNumpyEx.xlsx')
網(wǎng)站欄目:創(chuàng)新互聯(lián)Python教程:如何保存python程序所生產(chǎn)的數(shù)據(jù)?
網(wǎng)站地址:http://fisionsoft.com.cn/article/djcippd.html


咨詢
建站咨詢
