這兩天看完了Course上面的:
使用 Python 訪問網(wǎng)絡(luò)數(shù)據(jù)
https://www.coursera.org/learn/python-network-data/
寫了一些作業(yè),完成了一些作業(yè)。做些學(xué)習(xí)筆記以做備忘。
1.正則表達(dá)式 --- 雖然后面的課程沒有怎么用到這個(gè)知識(shí)點(diǎn),但是這個(gè)技能還是蠻好的。
附上課程中列出來的主要正則表達(dá)式的用法:
Python Regular Expression Quick Guide ^ Matches the beginning of a line $ Matches the end of the line . Matches any character \s Matches whitespace \S Matches any non-whitespace character * Repeats a character zero or more times *? Repeats a character zero or more times (non-greedy) + Repeats a character one or more times +? Repeats a character one or more times (non-greedy) [aeiou] Matches a single character in the listed set [^XYZ] Matches a single character not in the listed set [a-z0-9] The set of characters can include a range ( Indicates where string extraction is to start ) Indicates where string extraction is to end
特別的以前沒注意:From([0-9a-z]) 其實(shí)是取得符合整個(gè)規(guī)則的語句中()的部分。
并且 (.)并不表示任意字符而是只是.的意思。
附上作業(yè)編程:
import re def sumText(name): handle = open(name, 'r') sum = 0 for line in handle: nums = re.findall('[0-9]+', line) if len(nums) >=1: for num in nums: sum += int(num) return sum filedir = raw_input("imput fileName :") sum1 = sumText(filedir) print sum1
2.使用python建立socket鏈接
介紹了下socket,一個(gè)用于和應(yīng)用通訊的東西,每個(gè)網(wǎng)絡(luò)應(yīng)用都有對(duì)應(yīng)的端口號(hào),通過協(xié)議+主機(jī)名+端口就可以找到這個(gè)應(yīng)用進(jìn)行通訊了。
展示了使用telnet來獲取http服務(wù)的方式。
telnet www.rzrgm.cn 80 GET http://www.rzrgm.cn/webarn/p/6398989.html HTTP/1.0
不一定成功,覺得不是課程上面說的速度太慢的原因。
嗯附上自己知道比較簡(jiǎn)單的方式:
curl -XGET http://www.rzrgm.cn/webarn/p/6398989.html
或者 使用python直接建立url鏈接,代碼如下:
import socket mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) mysock.connect(('data.pr4e.org', 80)) mysock.send('GET http://data.pr4e.org/intro-short.txt HTTP/1.0\n\n') while True: data = mysock.recv(512) if ( len(data) < 1 ) : break print data; mysock.close()
再或者,使用瀏覽器的開發(fā)者工具也是一目了然的。
3.理解HTML并且進(jìn)行解析
由于網(wǎng)頁大部分都是html格式也就是超文本標(biāo)記語言,是大部分網(wǎng)頁展示的時(shí)候使用的語言,所以告訴了我們python里面也是有解析html 的包的:BeautifulSoup。
這個(gè)項(xiàng)目的鏈接如下:
https://www.crummy.com/software/BeautifulSoup/
使用詳情可以查看它。
然后就是代碼怎么使用了,還是自己作業(yè)的小小demo:
import urllib from BeautifulSoup import * url = raw_input('Enter - ') html = urllib.urlopen(url).read() soup = BeautifulSoup(html) sum = 0 trs = soup('tr') for tr in trs: if tr.span is not None: num = int(tr.span.contents[0]) sum += num print sum
4.webService 和xml
介紹了xml,可擴(kuò)展標(biāo)記語言。主要用來傳輸和存儲(chǔ)數(shù)據(jù)。可讀性會(huì)比較強(qiáng)。很多webservice的通訊協(xié)議都是用xml來設(shè)計(jì)的。
其中有一個(gè)schme的概念,比如我們以前會(huì)寫一些xsd文件來表示xml數(shù)據(jù)結(jié)構(gòu)中的約束,比如字段是否可輸還是必輸,比如字段類型,這是一個(gè)約束,也是類似于協(xié)議的東西。
schema也會(huì)有很多的標(biāo)準(zhǔn)的。
xml解析用的是python內(nèi)部的包:
xml.etree.ElementTree,將xml作為一個(gè)樹狀結(jié)構(gòu)來解析了,要獲取字段值要從根節(jié)點(diǎn)來數(shù)。
代碼 如下:
import urllib import xml.etree.ElementTree as ET url = raw_input("Enter location:") print 'Retrieving', url uh = urllib.urlopen(url) data = uh.read() print '\nRetrieved ', len(data), ' characters' tree = ET.fromstring(data) comments = tree.findall('.//comment') sum = 0 count = len(comments) print 'Count:', count for comment in comments: sum += int(comment.find('count').text) print 'Sum:', sum
5.json,api
這節(jié)談到了SOA,面向?qū)ο蠓?wù),大型的系統(tǒng)都會(huì)用到這個(gè),感覺上是各個(gè)系統(tǒng)中都有一層中間層用于通訊,通訊所用的數(shù)據(jù)協(xié)議,格式都是統(tǒng)一的,這樣可以互相通訊。當(dāng)然里面還有服務(wù)發(fā)現(xiàn)等問題需要考慮。但是有了SOA的架構(gòu)之后,各個(gè)不同的系統(tǒng)都可以通訊了。
api 課程中舉了google map的api和twitter的api,各個(gè)應(yīng)用可能都提供了api來進(jìn)行調(diào)用,application program interface 就是和一個(gè)系統(tǒng)通訊的接口。api的格式比較簡(jiǎn)單,使用REST風(fēng)格的調(diào)用。RESTFul風(fēng)格感覺可以再寫一篇文章了,可以看看他們直接的關(guān)系,但是我看到的api大都是網(wǎng)址+參數(shù)。就是這種 http://www.xxxx.com?para1=11&¶m2=11這種,應(yīng)該理解下來就是和前面說的協(xié)議+ 主機(jī)+ 端口+ 參數(shù)差不多了。
json介紹:json是一個(gè)簡(jiǎn)介的數(shù)據(jù)交換協(xié)議,只有一個(gè)版本,永遠(yuǎn)不會(huì)修改了,和xml比起來輕量很多,只有兩個(gè)數(shù)據(jù)格式map,list。其他可以參看(json.org)(寫這段chrome崩潰了3次,我也崩潰了。。。)然后就是loads才是解析string的,load是解析file的。
代碼附上:
import json import urllib url = raw_input('Enter location:') print 'Retrieving', url uh = urllib.urlopen(url) data = uh.read() print 'Retrieved', len(data) info = json.loads(data) print 'Count:', len(info['comments']) sum = 0 for comment in info['comments']: sum += int(comment['count']) print 'Sum: ', sum
api獲取然后解析json的:
import urllib import json serviceurl = 'http://python-data.dr-chuck.net/geojson?' while True: address = raw_input('Enter location:') if len(address) < 1 : break url = serviceurl + urllib.urlencode({'sensor': 'false', 'address': address}) print 'Retrieving ', url uh = urllib.urlopen(url) data = uh.read() print 'Retrieved',len(data),'characters' try: js = json.loads(str(data)) except: js = None if 'status' not in js or js['status'] != 'OK': print '==== Failure To Retrieve ====' print data continue print json.dumps(js, indent=4) print 'place_id:', js['results'][0]['place_id']
浙公網(wǎng)安備 33010602011771號(hào)