日本综合一区二区|亚洲中文天堂综合|日韩欧美自拍一区|男女精品天堂一区|欧美自拍第6页亚洲成人精品一区|亚洲黄色天堂一区二区成人|超碰91偷拍第一页|日韩av夜夜嗨中文字幕|久久蜜综合视频官网|精美人妻一区二区三区

RELATEED CONSULTING
相關(guān)咨詢
選擇下列產(chǎn)品馬上在線溝通
服務(wù)時(shí)間:8:30-17:00
你可能遇到了下面的問題
關(guān)閉右側(cè)工具欄

新聞中心

這里有您想知道的互聯(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))#在寫代碼的時(shí)候可以將讀取的內(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)建隨機(jī)值
 
#print(df.head(2))#查看數(shù)據(jù)框的頭部數(shù)據(jù),默認(rèn)不寫為前5行,小于5行時(shí)全部顯示;也可以自定義查看幾行
print(df.tail())##查看數(shù)據(jù)框的尾部數(shù)據(jù),默認(rèn)不寫為倒數(shù)5行,小于5行時(shí)全部顯示;也可以自定義查看倒數(shù)幾行
 
df.to_csv('D:/PythonWorkSpace/TestData/PandasNumpy.csv')#存儲到CSV中
#df.to_excel('D:/PythonWorkSpace/TestData/PandasNumpy.xlsx')#存儲到Excel中(需要提前導(dǎo)入庫 pip install openpyxl)

實(shí)例中保存豆瓣讀書的短評代碼如下:

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))#在寫代碼的時(shí)候可以將讀取的內(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()默認(rèn)為前5行
df.to_csv('D:/PythonWorkSpace/TestData/PandasNumpyCSV.csv')
#df.to_excel('D:/PythonWorkSpace/TestData/PandasNumpyEx.xlsx')


本文名稱:創(chuàng)新互聯(lián)Python教程:如何保存python程序所生產(chǎn)的數(shù)據(jù)?
轉(zhuǎn)載來源:http://www.dlmjj.cn/article/djcippd.html