日韩无码专区无码一级三级片|91人人爱网站中日韩无码电影|厨房大战丰满熟妇|AV高清无码在线免费观看|另类AV日韩少妇熟女|中文日本大黄一级黄色片|色情在线视频免费|亚洲成人特黄a片|黄片wwwav色图欧美|欧亚乱色一区二区三区

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()新建對(duì)象

寫入數(shù)據(jù)(這里使用的是爬取豆瓣讀書中一本書的豆瓣短評(píng)作為例子)

import requests
from lxml import etree
 
#發(fā)送Request請(qǐng)求
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()新建對(duì)象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')#存儲(chǔ)到CSV中
#df.to_excel('D:/PythonWorkSpace/TestData/PandasNumpy.xlsx')#存儲(chǔ)到Excel中(需要提前導(dǎo)入庫 pip install openpyxl)

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

import requests
from lxml import etree
 
#發(fā)送Request請(qǐng)求
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()新建對(duì)象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ù)?
文章網(wǎng)址:http://m.5511xx.com/article/djcippd.html