Python学习笔记之pandas索引列、过滤、分组、求和功能示例-创新互联
本文实例讲述了Python学习笔记之pandas索引列、过滤、分组、求和功能。分享给大家供大家参考,具体如下:

解析html内容,保存为csv文件
//www.jb51.net/article/162401.htm
前面我们已经把519961(基金编码)这种基金的历史净值明细表html内容抓取到了本地,现在我们还是需要 解析html,取出相关的值,然后保存为csv文件以便pandas来统计分析。
from bs4 import BeautifulSoup
import os
import csv
# 使用 BeautifulSoup 解析html内容
def getFundDetailData(html):
soup = BeautifulSoup(html,"html.parser")
rows = soup.find("table").tbody.find_all("tr")
result = []
for row in rows:
tds=row.find_all('td')
result.append({"fcode": '519961'
,"fdate": tds[0].get_text()
, "NAV": tds[1].get_text()
, "ACCNAV": tds[2].get_text()
, "DGR": tds[3].get_text()
, "pstate":tds[4].get_text()
, "rstate": tds[5].get_text()
}
)
return result
# 把解析之后的数据写入到csv文件
def writeToCSV():
data_dir = "../htmls/details"
all_path = os.listdir(data_dir)
all_result = []
for path in all_path:
if os.path.isfile(os.path.join(data_dir,path)):
with open(os.path.join(data_dir,path),"rb") as f:
content = f.read().decode("utf-8")
f.close()
all_result = all_result + getFundDetailData(content)
with open("../csv/519961.csv","w",encoding="utf-8",newline="") as f:
writer = csv.writer(f)
writer.writerow(['fcode', 'fdate', 'NAV', "ACCNAV", 'DGR', 'pstate', "rstate"])
for r in all_result:
writer.writerow([r["fcode"], r["fdate"], r["NAV"], r["ACCNAV"], r["DGR"], r["pstate"], r["rstate"]])
f.close()
另外有需要云服务器可以了解下创新互联scvps.cn,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。
文章题目:Python学习笔记之pandas索引列、过滤、分组、求和功能示例-创新互联
标题网址:http://jxruijie.cn/article/idpgc.html
