1. 程式人生 > >python資料科學入門與分析

python資料科學入門與分析

python資料科學入門與分析

第二章 資料科學的Python核心

  • 基本的內建str函式

1.print("hello".capitalize());將第一個字元轉化為大寫,其他字元轉化為小寫

2.print("hello world ".strip());:注意lstrip,rstrip,strip的用法

3.print("www.baidu.com".split(".")):會用split裡面的分割符進行分割

4print("a".islower());:islower,isupper,isspace,isdigit,isalpha的使用

5.print("-".join("210.34.148.51".split(".")));: #.join函式僅在字串之間進行插入,在字串的開頭一個末尾都不進行插入

多行的註釋方式為ctrl+1

#計數器的運用
from collections import Counter
phrase = "世界 你 好,你好! 你好"
cntr = Counter(phrase.split())
print(cntr.most_common)

8.爬取資料,並注意相應的異常處理機制

#這裡是從web中爬取相應的資料
#這裡一定要有相應的異常處理機制 try except
import urllib.request try: with urllib.request.urlopen("http://www.networksciencelab.com") as doc: html = doc.read(); print("yes") except: print("couldn't not open file");
  • re模組的學習(正則表示式)

首先,你應該熟記正則表示式的各種表示形式,附下圖
在這裡插入圖片描述示例
1.re.findall
在這裡插入圖片描述
2.re.split
在這裡插入圖片描述
3.re.sub(pattern,repl,string),用 repl替換字串中的所有非重疊匹配部分
在這裡插入圖片描述

  • globbing匹配特定檔名和萬用字元的過程

示例 glob函式
在這裡插入圖片描述
在這裡插入圖片描述

  • Pickling模組的學習

pickle模組用於實現序列化-將任意的python資料結構儲存到一個檔案中,並將其作為python表示式讀回。

作用:python程式執行中得到了一些字串,列表,字典等資料,想要長久的儲存下來,方便以後使用,而不是簡單的放入記憶體中關機斷電就丟失資料。

import pickle 
a = {" name ": "Tom", "age": "40"}
with open('text.txt', 'wb') as file:
    pickle.dump(a, file)
with open('text.txt', 'rb') as file2:
    b = pickle.load(file2)
print(type(b))
print(b)

其實,就是將資料按照某種格式存入檔案之中,而不是以字串的形式讀入的。

第三章 使用文字資料

Beautifulsoup的使用

from bs4 import BeautifulSoup
from urllib.request import urlopen
soup3 = BeautifulSoup(urlopen("https://msdn.itellyou.cn/"),"lxml")
print(soup3)

效果
在這裡插入圖片描述使用soup.get_text()方法可得到標記文件中取出了所有標籤的文字部分
在這裡插入圖片描述soup的函式:soup.find(),soup.find_all()

##beautifulsoup模組的運用
from bs4 import BeautifulSoup
from urllib.request import urlopen
soup3 = BeautifulSoup(urlopen("https://msdn.itellyou.cn/"),"lxml")
##print(soup3.get_text())

#soup4 = soup3.find(id = "mySmallModalLabel")
#print(soup4)

#links = soup3.find_all("a")
#firstLink = links[0]["href"]
#print(firstLink)

CSV檔案

CSV是一種結構化文字檔案格式,用於儲存和轉移表格資料。一個CSV檔案由表示變數的列和表示記錄的行組成。

JSON

Json(JavaScript Object Notation)是一種輕量級的資料交換格式,Json支援原子資料型別,陣列,物件,鍵值對

將複雜資料儲存到Json檔案中的操作稱為序列化,相應的反向操作則稱為反序列化

學習的網站:菜鳥教程

總是要通過一定的擴充套件,才能真正的掌握一些 東西的。
編碼json資料

#編碼為json資料
import json
data = [ { 'a' : 1, 'b' : 2, 'c' : 3, 'd' : 4, 'e' : 5 } ]
json = json.dumps(data)
print(json)

解碼json資料

import json
jsonData = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
text = json.loads(jsonData)
print(text)

也許,你到這裡對json也還是一知半解,只知道它對資料格式的轉換還是挺有用的。