2019年11月23日 星期六

python3.8 新特性async實現自動化爬蟲功能


下面程式碼實現在指定URL下抓取HTML頁面裡包含javascript腳本生成quote節點後的訊息。
import asyncio
from pyppeteer import launch
from pyquery import PyQuery as pq

async def main():
    print ('start main()')
    browser = await launch()
    print('browser ready')
    page = await browser.newPage()
    print('Page ready')
    await page.goto('http://quotes.toscrape.com/js/')
    print('goto ready')
    doc = pq(await page.content())
    print('pq ready')
    print('Quotes:', doc('.quote').length)
    await browser.close()
    print('browser closed')


if __name__ == '__main__':
    if asyncio.iscoroutinefunction(main):
        asyncio.get_event_loop().run_until_complete(main())
    else:
        main()

好久沒有更新blogger了,來新增一波內容
pyppeteer :https://github.com/miyakogi/pyppeteer
chromium automation library

PyQuery: jquery-like library for python
async: keyword for coroutine, to write concurrent code in python3.8

2018年1月6日 星期六

神經網絡的普適性

啟發來源:
# https://github.com/mxjl620/reading_note/blob/master/Neural_Network_and_Deep_Learning/%E7%AC%AC%E5%9B%9B%E7%AB%A0_%E7%A5%9E%E7%BB%8F%E7%BD%91%E7%BB%9C%E5%8F%AF%E4%BB%A5%E6%8B%9F%E5%90%88%E4%BB%BB%E4%BD%95%E5%87%BD%E6%95%B0%E7%9A%84%E5%8F%AF%E8%A7%86%E5%8C%96%E8%AF%81%E6%98%8E.md

神經網絡的普適性:神經網絡可以擬和任意函數。


數學證明:
=========
# 基礎證明普適性
Approximation by superpositions of a sigmoidal function, by George Cybenko (1989).

# 採用Stone-Weierstrass定理的方式證明,包含hahn-Banach Theory、Riesz Representation、Fourier Analysis
Multilayer feedforward networks are universal approximators, by Kurt Hornik, Maxwell Stinchcombe, and Halbert White (1989)

# "神經網絡可以擬合任何函數"的普適性說明:
1. 增加隐藏神经元的个数,就能得到更好的结果,證明方式與微積分的趨近的delta-eplison表達雷同。
2. sigmoid神經元組成的網絡可以計算任意函數

sigmoid function的在神經元節點的weight足夠大時,可以擬合讓他趨近於step function。

2017年10月3日 星期二

how to start your chinese NLP journey?

# how to import chinese corpus for NLP
# http://cpmarkchang.logdown.com/posts/184192-python-nltk-sinica-treebank
# http://ckip.iis.sinica.edu.tw/CKIP/treebank.htm
# http://museum02.digitalarchives.tw/ndap/2002/SinicaTreebank/ckip.iis.sinica.edu.tw/CKIP/tr/201301_20140813.pdf
>>> from nltk.corpus import sinica_treebank
>>> import nltk

# get all treebank words in one time
>>> sinica_treebank.words()
['\xe4\xb8\x80', '\xe5\x8f\x8b\xe6\x83\x85', ...]

# get tagged_words and sentences in treebank
>>> sinica_treebank.tagged_words()
[('\xe4\xb8\x80', 'Neu'), ('\xe5\x8f\x8b\xe6\x83\x85', 'Nad'), ...]
>>> sinica_treebank.sents()[15]
['\xe5\xa4\xa7\xe8\x81\xb2', '\xe7\x9a\x84', '\xe5\x8f\xab', '\xe8\x91\x97']

# get the grammar tree
>>> sinica_treebank.parsed_sents()[15]
Tree('VP', [Tree('V\xe2\x80\xa7\xe5\x9c\xb0', [Tree('VH11', ['\xe5\xa4\xa7\xe8\x81\xb2']), Tree('DE', ['\xe7\x9a\x84'])]), Tree('VE2', ['\xe5\x8f\xab']), Tree('Di', ['\xe8\x91\x97'])])

# draw the grammar tree
>>> sinica_treebank.parsed_sents()[15].draw()

# get concordance
>>> sinica_text=nltk.Text(sinica_treebank.words())
>>> sinica_text.concordance('我')

# frequency distribution
>>> sinica_fd=nltk.FreqDist(sinica_treebank.words())
>>> top100=sinica_fd.items()[0:100]
>>> for (x,y) in top100:
>>>     print x,y

# how to list all docs in a corpus
# http://www.burnelltek.com/blog/0376c9eac69611e6841d00163e0c0e36
import nltk
from nltk.corpus import gutenberg
print(gutenberg.fileids())

# corpus from web
from nltk.corpus import webtext
print(webtext.fileids())

# corpus for inaugural
from nltk.corpus import inaugural
print(inaugural.fileids())

# corpus from chat
from nltk.corpus import nps_chat
print(nps_chat.fileids())

# how to get a document from a corpus
emma = gutenberg.words("austen-emma.txt")
print(emma)

# entropy, point mutual information, perplexity are measures for sentimental classification

# how to use conditional frequency Distribution
# http://www.burnelltek.com/blog/e08e0bbecb1811e6841d00163e0c0e36
import nltk
from nltk.corpus import brown
pairs = [(genre, word) for genre in brown.categories() for word in brown.words(categories=genre)]
cfd = nltk.ConditionalFreqDist(pairs)

# how to generate all possible bigrams
sent = ['I', 'am', 'a', 'good', 'man']
print(list(nltk.bigrams(sent)))


# how to use conditional frequency distribution
# http://www.burnelltek.com/blog/e08e0bbecb1811e6841d00163e0c0e36
import nltk
from nltk.corpus import brown
pairs = [(genre, word) for genre in brown.categories() for word in brown.words(categories=genre)]
cfd = nltk.ConditionalFreqDist(pairs)

# show conditions for conditional frequency distribution
print(cfd.conditions())

# display a table for specified conditions and term frequency
genres = ['news', 'religion', 'hobbies', 'science_fiction', 'romance', 'humor']
modals = ['can', 'could', 'may', 'might', 'must', 'will']
cfd.tabulate(conditions=genres, samples=modals)

# display a plot for conditional frequency distribution
cfd.plot(conditions=genres, samples=modals)

# how to get the frequency distribution with specified vacabularies from bigrams
text = brown.words(categories='news')
bigrams_words = nltk.bigrams(text)
cfd = nltk.ConditionalFreqDist(bigrams_words)
fd = cfd['can']
fd.plot(10)

# how to process pos tags
import nltk
words = nltk.word_tokenize('And now for something completely different')
print(words)
word_tag = nltk.pos_tag(words)
print(word_tag)

# nltk pos tagging for Chinese
nltk.word_tokenize(text):对指定的句子进行分词,返回单词列表
nltk.pos_tag(words):对指定的单词列表进行词性标记,返回标记列表
CategorizedTaggedCorpusReader::tagged_words(fileids, categories):该方法接受文本标识或者类别标识作为参数,返回这些文本被标注词性后的单词列表
CategorizedTaggedCorpusReader::tagged_sents(fileids, categories):该方法接受文本标识或者类别标识作为参数,返回这些文本被标注词性后的句子列表,句子为单词列表
SinicaTreebankCorpusReader::tagged_words(fileids):该方法接受文本标识作为参数,返回文本被标注词性后的单词列表
SinicaTreebankCorpusReader::tagged_sents(fileids):该方法接受文本标识作为参数,返回文本被标注词性后的句子列表,句子为单词列表

# how to stats all segmented chinese words?
python -m jieba 1.txt -q | tr '/' '\n' | sort | uniq -c
python -m jieba 1.txt -q | tr '/' '\n' | sed 's/^[ \t]//' # clean leading spaces in each line

# how to calculate the words diversity
numerator=$(python -m jieba 1.txt -q | tr '/' '\n' | sed 's/^[ \t]//' | sort  | uniq | wc -l) # stats how many uniq words in the doc
denominator=$(python -m jieba 1.txt -q | tr '/' '\n' | sed 's/^[ \t]//' | sort | wc -l # stats how many words in the doc)
words_diversity = $numerator / $denominator

# online code search on command line
https://github.com/stayhigh/how2
pip install how2

https://github.com/gautamkrishnar/socli
sudo apt-get install python python-pip
sudo pip install socli

https://www.npmjs.com/package/stack-overflow-search
 npm install -g stack-overflow-search

2017年5月25日 星期四

機器學習實戰 - kNN算法 - 2

kNN演算法

簡述:
kNN算法非常直覺,根據統計新的資料點離原本的k個最近的資料點的分類的出現數量與距離進行判斷,藉此分析新的資料所屬的分類。

主要應用:約會網站、手寫數字辨識系統
算法優點:精度高、對異常值不敏感、不假定輸入數據
適用資料範圍類型:數值型與標準型

參考來源:http://www.ifight.me/273/
kNN算法步驟:



kNN演算法的基本思路:在給定新資料后,考慮在訓練資料點中與該新資料點距離最近(最相似)的 K 個資料點,根據這 K 個資料點所屬的類別判定所屬的分類類別,具體的演算法步驟如下:


  1. 計算已知類別資料及當中的點與當前點之間的距離
  2. 按照距離遞增次序排列
  3. 選取與當前點距離最小的k個點
  4. 確定前k個點所在類別的出現頻率
  5. 返回前k個點出現高頻的類別作為當前點的預測分類
距離公式可採用下面多種距離,一般建議Mahalanobis distance效果較佳。

關於更多Mahalanobis distance資訊: https://en.wikipedia.org/wiki/Mahalanobis_distance


下面附上常用的距離公式列表:

  1. 歐氏距離 (各個維度距離重要度均等)
  2. 曼哈頓距離 (Manhattan distance又稱city block distance,格子距離)
  3. 切比雪夫距離 (Chebyshev Distance,等同國際象棋國王與棋子的行走距離)
  4. 閔可夫斯基距離 (Minkowski Distance)
    當p=1時,就是曼哈頓距離
    當p=2時,就是歐氏距離
    當p→∞時,就是切比雪夫距離
  5. 標準化歐氏距離 (根據傳統歐氏距離的每個維度標準差變量進行標準化)
  6. 馬氏距離 (Mahalanobis Distance
    @解決思想:由於各維度權重相同所造成的分類誤判、排除變量之間的相關性的干擾
    @數學原理:距離近的加權高、距離遠的加權低、最後算總值。
  7. 夾角餘弦(Cosine Similarity,衡量向量之間的差異)
  8. 漢明距離 (Hamming distance,兩個等長字串的最小替換次數,應用在訊息編碼)
  9. 傑卡德距離 & 傑卡德相似係數
    (Jaccard similarity coefficient,兩集合交集數除以聯集數,應用於集合相似度的計算)
    Jaccard distance = 1 - Jaccard similarity coefficient
  10. 相關係數 & 相關距離 (Correlation coefficient, Correlation distance)
    可用於計算線性相關度。
  11. 信息熵 (Information Entropy,用於衡量分布的分散程度的度量,分佈越集中entropy就越小)


機器學習實戰 - 機器學習的應用步驟 - 1


由於身邊很多朋友想要接觸機器學習,卻不知道如何開始與應用,所以撰寫簡易的入門文讓新手理解如何應用機器學習的演算法於現實世界的問題。也分享個人經驗。

根據Machine Learning in Action書裡面的講解,可分成下面步驟:

  1. 收集數據
  2. 準備輸入數據
  3. 分析輸入數據
  4. 訓練算法
  5. 測試算法
  6. 使用算法 
收集數據部分:個人是使用python透過scrapy框架撰寫網絡爬蟲程式,好用便捷。
準備輸入數據:可透過numpy或pandas裡面讀取文件的API,並確認Load資料正確無誤。
分析輸入數據:查看資料是否有異常值、分析特徵的數值分佈、使用matplotlib將資料視覺化
訓練算法:根據資料抽取知識跟信息後,根據資料特性來選擇適合的機器學習演算法。
測試算法:設計評估算法,透過accuracy與recall數值評分。
使用算法:如何設計整個應用的流程pipeline。

建議使用python語言,提供適用的字串處理、數值運算、文本分析工具、機器學習套件等。
下面是IEEE選出的TOP 10演算法,可先以這些算法著手學習:






scikit-learn 機器學習套件 - 分析 supervised machine learning algorithm 效率

參考資料: http://scikit-learn.org/

套件說明:
scikit-learn此python套件非常適合用於機器學習領域。
機器學習領域一般分為:監督式學習、非監督式學習、增強式學習等
在能拿過去資料並有相關特徵標籤的分析案例而言,一般採用監督式學習演算法。

由於過去研究SVM是當前分類accuracy比較高的算法, 這次透過scikit裡面的內容驗證監督式學習演算法的效率,分析各個算法的效率。

分析程式碼與資源:
相關程式碼參閱下面連結:
http://scikit-learn.org/stable/auto_examples/classification/plot_classifier_comparison.html#sphx-glr-auto-examples-classification-plot-classifier-comparison-py

裡面的程式碼片段可以看到所有羅列出來的算法。
names = ["Nearest Neighbors", "Linear SVM", "RBF SVM", "Gaussian Process",
         "Decision Tree", "Random Forest", "Neural Net", "AdaBoost",
         "Naive Bayes", "QDA"]

下面是分析結果示意圖,右下角數值為accuracy:

實驗結論:
實驗中採用三種特性的dataset,第一個是部分特徵數值混在一起的、第二個是線性不可分的資料集合、第三個是簡易可以線性分割的資料集。由圖可知RBF-SVM是在這次實驗當中表現最好的一個算法。

關鍵解析:
重點在於SVM採用的kernel function,解決的線性不可分的資料集合所產生的問題。
其中kernel function原理就是透過內積運算原理將較低維度的空間資料及轉換到高維度的空間,使其資料集合較能夠線性可分,下方示意圖為2維轉換到3維的空間轉換示意圖。

關於kernel function原理請參閱下面連結: https://ireneli.eu/2016/09/13/two-sample-problem2-kernel-function-feature-space-and-reproducing-kernel-map/
關於RBF kernel 請參考:https://read01.com/2xMOa4.html





2017年2月12日 星期日

如何快速製作terminal的動作成gif動畫圖檔?

開發程式常常會需要說明使用方法,其中一個就是製作在terminal上面的動畫圖檔
下面推薦兩款ttygif與ttystudio使用。


各個作業系統的安裝方式可參考下面連結:
https://github.com/icholy/ttygif
https://github.com/chjj/ttystudio



下面以mac osx作為範例說明如何安裝與使用

# ttygif 安裝與使用
brew install ttygif
ttyrec recording
ttygif recording 

# ttystudio 安裝與使用

npm install ttystudio
ttystudio output.txt --log # 執行此行指令便開始錄製,使用ctrl+Q退出錄製並製作gif檔案。

2016年12月28日 星期三

Machine Learning Cheatsheet

機器學習常用的cheatsheets方便快速複習程式工具。
透過python可以加速很多的操作流程,另外也有附上許多的相關資料分析工具。
來源:http://www.kdnuggets.com/2015/07/good-data-science-machine-learning-cheat-sheets.html


Cheat sheets for Python: 
Python is a popular choice for beginners, yet still powerful enough to back some of the world’s most popular products and applications. It's design makes the programming experience feel almost as natural as writing in English. Python basics or Python Debugger cheatsheets for beginners covers important syntax to get started. Community-provided libraries such as numpy, scipy, sci-kit and pandas are highly relied on and the NumPy/SciPy/Pandas Cheat Sheet provides a quick refresher to these. 

Cheat sheets for R: 
The R's ecosystem has been expanding so much that a lot of referencing is needed. The R Reference Card covers most of the R world in few pages.The Rstudio has also published a series of cheatsheets to make it easier for the R community. The data visualization with ggplot2 seems to be a favorite as it helps when you are working on creating graphs of your results. 

Cheat sheets for MySQL & SQL: 
For a data scientist basics of SQL are as important as any other language as well. Both PIG and Hive Query Language are closely associated with SQL- the original Structured Query Language. SQL cheatsheets provide a 5 minute quick guide to learning it and then you may explore Hive & MySQL!

Cheat sheets for Spark: 
Apache Spark is an engine for large-scale data processing. For certain applications, such as iterative machine learning, Spark can be up to 100x faster than Hadoop (using MapReduce). The essentials of Apache Spark cheatsheet explains its place in the big data ecosystem, walks through setup and creation of a basic Spark application, and explains commonly used actions and operations.

Cheat sheets for Hadoop & Hive: 
Hadoop emerged as an untraditional tool to solve what was thought to be unsolvable by providing an open source software framework for the parallel processing of massive amounts of data. Explore the Hadoop cheatsheets to find out Useful commands when using Hadoop on the command line. A combination of SQL & Hive functions is another one to check out.

Cheat sheets for Machine learning: 
We often find ourselves spending time thinking which algorithm is best? And then go back to our big books for reference! These cheat sheets gives an idea about both the nature of your data and the problem you're working to address, and then suggests an algorithm for you to try.

Cheat sheets for Django : 
Django is a free and open source web application framework, written in Python. If you are new to Django, you can go over these cheatsheets and brainstorm quick concepts and dive in each one to a deeper level.

2016年4月13日 星期三

doxygen常見問題

設定wizard時需要注意的細節:
  • Step1設定working directory時,不可使用複製貼上字串的方式設定指定目錄
  • 切記需要使用DOT_PATH為/usr/local/bin,若無設定則會在run doxygen之後發生下述錯誤訊息 sh: dot: command not found,可透過安裝graphviz的方式並確認DOT_PATH設定無誤。

關於相關指令用法以及註解撰寫格式可參照:

GNU parallel 應用範例

說明範例採用1.txt與2.txt作為輸入檔案範例:
檔案1.txt內容為
A
B
C
檔案2.txt內容為:
D
E
F

指令範例1:
parallel echo ::: $(cat 1.txt) ::: $(cat 2.txt) 2>/dev/null

輸出:
B F
C D
B E
B D
C E
A F
A E
A D
C F

指令範例2:
parallel -k echo ::: $(cat 1.txt) ::: $(cat 2.txt) 2>/dev/null

輸出:
A D
A E
A F
B D
B E
B F
C D
C E
C F

2016年4月12日 星期二

使用lynx快速取得網頁的超連結並存成清單,並搭配wget下載URL清單檔案

簡介

常常在製作爬蟲程式時,相當需要快速將單頁網頁上面出現的所有超連結存成清單,以方便後續利用wget程式。

殺手級的下載工具的功能主要有:
  1. 找出指定網頁的所有相關URL連結並存成文件
  2. 使用wget指令下載所有相關URL
  3. 使用GNU parallel平行執行多個執行工作
實際範例

下面以gstreamer官方網站的網址作為舉例:
https://gstreamer.freedesktop.org/data/events/gstreamer-conference/2015/

1)利用如下指令快速輸出URL清單列表:
lynx  -dump https://gstreamer.freedesktop.org/data/events/gstreamer-conference/2015/ |grep http|awk '{print $2}' > urls.txt
2)使用wget指令下載URL清單:
wget -i urls.txt 
3)使用GNU parallel工具平行執行多個工作
關於parallel指令使用方法參考:https://www.gnu.org/software/parallel/parallel_tutorial.html
cat urls.txt | parallel "wget -i {}"

將(1)(2)(3)三個步驟觀念整合後可轉寫成shell將其自動化。



補充(若想要監控目錄的下載狀況,可透過watch指令觀察指定目錄的文件狀態):
watch -d ls

補充(若發生zombie的狀況,可使用下列指令清除zombie的parent process): 
kill $(ps -A -ostat,ppid | awk '/[zZ]/{print $2}')

由於zombie process已經結束,所以無法使用kill指令刪除,可透過終結parent process的方式刪除zombie。(當parent process終結時,zombie將繼承init,並且parent process將會等待init並且清除在process table上面的記錄)

參考來源:http://stackoverflow.com/questions/16944886/how-to-kill-zombie-process

A zombie is already dead, so you cannot kill it. To clean up a zombie, it must be waited on by its parent, so killing the parent should work to eliminate the zombie. (After the parent dies, the zombie will be inherited by init, which will wait on it and clear its entry in the process table.) If your daemon is spawning children that become zombies, you have a bug. Your daemon should notice when its children die and wait on them to determine their exit status.

2016年4月11日 星期一

快速調整man指令的分頁工具// How to check and set pager for 'man' command?

快速調整man指令的分頁工具

常見的分頁工具如下兩個:
  • /bin/more
  • /bin/less
如何快速使用指令更改:
  • 使用file指令查詢連結
  • 使用readlink -f 快速查找最終連結到的檔案
  • 若要重新設定連結的指定位置可以使用ln -sf /etc/alternatives/pager /bin/more其他pager
  • (由於/etc/alternatives/pager已經存在,若要重新設定連結需要搭配-f參數)


2016年4月3日 星期日

NAT 與 穿越防火牆技術


參考來源:http://www.cs.nccu.edu.tw/~lien/Writing/NGN/firewall.htm

關於Network Address Translation (NAT):
  • Why NAT? 解決IPv4地址短缺的方案
  • What is NAT? IP封包通過路由器或防火牆時重寫源IP地址或目的IP地址的技術。
  • How many NAT types? 
    • Full cone NAT
    • Address-Restricted cone NAT
    • Port-Restrict cone NAT
    • Symmetric NAT
Full cone NAT,亦即著名的一對一(one-to-one)NAT
  • 一旦一個內部地址(iAddr:port1)映射到外部地址(eAddr:port2),所有發自iAddr:port1的包都經由eAddr:port2向外發送。任意外部主機都能通過給eAddr:port2發包到達iAddr:port1
Full Cone NAT.svg
Address-Restricted cone NAT
  • 一旦一個內部地址(iAddr:port1)映射到外部地址(eAddr:port2),所有發自iAddr:port1的包都經由eAddr:port2向外發送。任意外部主機(hostAddr:any)都能通過給eAddr:port2發包到達iAddr:port1的前提是:iAddr:port1之前發送過包到hostAddr:any. "any"也就是說埠不受限制
Restricted Cone NAT.svg
Port-Restricted cone NAT
類似受限制錐形NAT(Restricted cone NAT),但是還有埠限制。
  • 一旦一個內部地址(iAddr:port1)映射到外部地址(eAddr:port2),所有發自iAddr:port1的包都經由eAddr:port2向外發送。一個外部主機(hostAddr:port3)能夠發包到達iAddr:port1的前提是:iAddr:port1之前發送過包到hostAddr:port3.
Port Restricted Cone NAT.svg
Symmetric NAT(對稱NAT)
  • 每一個來自相同內部IP與埠,到一個特定目的地地址和埠的請求,都映射到一個獨特的外部IP位址和埠。
    同一內部IP與埠發到不同的目的地和埠的信息包,都使用不同的映射
  • 只有曾經收到過內部主機封包的外部主機,才能夠把封包發回
Symmetric NAT.svg

常見穿越防火牆/NAT的相關技術:
  • UPnP(Universal Plug and Play)
  • STUN(Simple Traversal of UDP Through Network Address Translators)-RFC 3489
  • TURN(Traversal Using Relay NAT)
  • ALG(Application Layer Gateway)
  • ICE(Interactive Connectivity Establish)
UPnP缺點 :NAT必須支援UPnP協定
STUN缺點:Symmetric NAT無法穿透
TURN缺點 : TURN server需要承受連線頻寬
ALG缺點:基於網路安全,網管人員將不會接受用戶的應用程式控制他們的NAT


相關開源工具:
pystun, 提供查詢外部IP位置及NAT型別:https://github.com/jtriley/pystun
pjnath, Open Source ICE, STUN, and TURN Library: http://www.pjsip.org/pjnath/docs/html/

2016年3月20日 星期日

研究如何突破Koding VM always on限制

Koding是什麼?
提供開發者雲端開發環境的服務商,提供註冊用戶免費使用一個虛擬機並提供基本設定檔案與環境。如果有需要使用免費的 VM練習使用網頁,可以前往https://koding.com/註冊帳號,註冊完畢後就可以擁有免費的虛擬機器提供用戶練習程式。但美中不足的部分是免費版本的帳號每30分鐘會關閉虛擬機器,付費版本才會提供Keep VM always on的功能。

略過註冊的部分,此處提供登入Koding後畫面:


點擊觀看左側koding-vm-0相關設定,General標籤裡面出現Keep VM always on,但免費用戶無法使用:


官方建議免費版本用戶透過登入koding網站讓VM機器保持開啟狀態,於是開始思考如何突破限制。本次研究嘗試網頁自動化工具selenium,撰寫程式讓電腦每30分鐘內自動化登入,藉由此法成功保持VM持續開機!!本次採用的方案使用selenium進行網頁自動化登入koding帳號之後啟用VM

python範例程式碼:
https://github.com/stayhigh/koding-vm-active-selenium/blob/master/koding_login_active_vm.py

使用selenium網頁自動化的功能提到兩種重要的等待功能(wait)之間的差異:
explicit wait (wait for certain conditions, less than the specified time seconds)
implicit wait (DOM polling, waiting for elements)
官方網站也特別說明請勿混用,會造成等待時間增加。
http://www.seleniumhq.org/docs/04_webdriver_advanced.jsp


本次範例程式碼當中採用的自動化工具是selenium,但還有其他自動化工具可以參考:

xdotool: 應用shell script相當方便,可用於模擬鍵盤與滑鼠行為
關於python的鍵盤與滑鼠自動化的模組羅列如下:

 - pyautogui: python的模組,主要提供控制鍵盤與滑鼠的GUI自動化功能,
pyautogui安裝方法:
On Windows, there are no other modules to install.
On OS X run sudo pip3 install pyobjc-framework-Quartz, sudo pip3 install pyobjc-core, and then sudo pip3 install pyobjc.
On Linux, run sudo pip3 install python3-xlib, sudo apt-get install scrot, sudo apt-get install python3-tk, and sudo apt-get install python3-dev. (Scrot is a screenshot program that PyAutoGUI uses.)
pyautogui詳情參考:https://automatetheboringstuff.com/chapter18/

關於其他python自動化工具請參考:http://schurpf.com/python-automation/
- SendKeysCtypes
- PYHK
- win32gui
- pywinauto
- mouse

HTML的script 標籤三個屬性說明! 請愛用 async

參考來源:http://peter.sh/experiments/asynchronous-and-deferred-javascript-execution-explained/

Asynchronous and deferred JavaScript execution explained


The HTML <script> element allows you to define when the JavaScript code in your page should start executing. The “async” and “defer” attributes were added to WebKit early September. Firefox has been supporting them quite a while already. Does your browser support the attributes?

- Normal execution <script>
- This is the default behavior of the <script> element. Parsing of the HTML code pauses while the script is executing. For slow servers and heavy scripts this means that displaying the webpage will be delayed.

- Deferred execution <script defer>
- Simply put: delaying script execution until the HTML parser has finished. A positive effect of this attribute is that the DOM will be available for your script. However, since not every browser supports defer yet, don’t rely on it!

- Asynchronous execution <script async>
- Don’t care when the script will be available? Asynchronous is the best of both worlds: HTML parsing may continue and the script will be executed as soon as it’s ready. I’d recommend this for scripts such as Google Analytics.


根據上面英文原文重點整理,重述script標籤的三種屬性:
- <script>
- <script defer>
- <script async>

上圖當中出現三個名詞:parser|net|execution
- net 代表下載該javascript檔案的時段
- execution 代表執行該javascript檔案的時段
- parser代表http client 解析的過程的時段

可以看到async的屬性相當在設計網頁場景當中相當實用,parser解析時同時將下載該javascript檔案。請愛用async!

使用selenium自動化登入github網頁

主要使用到以下工具完成自動化登入github網頁:
selenium:網頁自動化工具,請參考 http://www.seleniumhq.org/
python 的getpass模組:提供使用者輸入密碼功能

範例程式碼已放置於stayhigh的github空間:
https://github.com/stayhigh/github-login-selenium/blob/master/github_login.py

程式碼用途:
場景為redhero0702@gmail.com作為用戶名稱登入github網站,如有需要可將
github_account = "redhero0702@gmail.com"
改成您的github用戶名即可,假設你的用戶名稱為your_github_account@gmail.com
github_account = "your_github_account@gmail.com"


2016年3月14日 星期一

Python Scrapy 快速攻略與教學


# 安裝google chrome plugin,SelectorGadget快速取得selector與xpath等相關資訊,網頁爬蟲特別實用
# 安裝firefox plugin,sqlite manager觀看資料庫內容:http://www.minwt.com/website/server/4964.html

#開啟apple新的scrapy專案
stayhigh@stayhighnet:/Users/stayhigh/projects/apple  $  scrapy startproject apple

#執行apple的scrapy專案
stayhigh@stayhighnet:/Users/stayhigh/projects/apple  $  scrapy crawl apple

#執行apple的scrap專案,並且將輸出a.json的json格式檔案
stayhigh@stayhighnet:/Users/stayhigh/projects/apple  $  scrapy crawl apple -o a.json -t json

#執行分段爬蟲任務並放置相關資料於job1目錄
stayhigh@stayhighnet:/Users/stayhigh/projects/apple  $  scrapy crawl apple -s JOBDIR=job1

#觀看apple專案目錄結構
- crawler.py為使用者自行定義的爬蟲程式,藉由繼承scrapy.Spider類別進行網頁抓取
- items.py 用於定義資料欄位
- pipeline.py 用於定義爬蟲程式的控制流程
- settings.py 設定檔,用於設定啟用的功能,如常見的pipeline功能,並切記設定時指定pipeline.py當中的apple.pipelines.ApplePipeline

ITEM_PIPELINES {
    'apple.pipelines.ApplePipeline'300,
}

stayhigh@stayhighnet:/Users/stayhigh/projects/apple  $ tree
.
├── a.json
├── apple
│   ├── __init__.py
│   ├── __init__.pyc
│   ├── items.py
│   ├── items.pyc
│   ├── pipelines.py
│   ├── settings.py
│   ├── settings.pyc
│   └── spiders
│       ├── __init__.py
│       ├── __init__.pyc
│       ├── crawler.py
│       └── crawler.pyc
└── scrapy.cfg

#如何實現多網頁爬取功能
from scrapy.spiders import CrawlSpider

# crawler.py內的爬蟲類別繼承CrawlSpider
class AppleCrawler(CrawlSpider):



2014年2月22日 星期六

寫C語言需要注意的型別問題 portablility


參考來源:http://blog.urdada.net/2008/04/18/85/

不同位元(32 bits, 64 bits)的作業系統下面的型別大小不一定相同


1.《Bypass the 2GB file size limit on 32-bit Linux => 64-bit 的系統下,long 的長度也是各自表述的!
2.int 的大小即使到了 64-bit 的機器上,大部分的系統仍然使用 4 bytes 的大小而已,這主要是為了避免程式從 32-bit 系統轉換到 64-bit 系統需要修改太多地方
3.參考 Wikipedia: 64-bit data models 的說明
絕大多數的 UNIX 系統在 64-bit 下面採用 LP64 這種 data model,此時 long 就不再是固定為 4 bytes 大小,而是變成 8 bytes 的大小了!
然而,Win64 卻不是使用 LP64,而是採用 LLP64 這個 data model,這時候 long 的大小仍然還是 4 bytes

Many 64-bit compilers today use the LP64 model (including Solaris, AIX, HP, Linux, Mac OS X, and IBM z/OS native compilers). Microsoft's VC++ compiler uses the LLP64 model.
兩種 data model 的最大差異點就是 long 這個資料型態的大小,LP64 是 64-bit,而 LLP64 則是 32-bit
LLP64 data model 基本上可以說跟 32-bit 的系統一樣,唯一差別只有位址(pointer)改成了 64-bit 而已。資料物件(class, structure) 等如果沒有包含 pointer 的成員的話,整個物件的大小是與 32-bit 系統一樣的!
而 LP64 則是除了位址(pointer)改成 64-bit 之外,long 的大小也變成了 64-bit 大小。所以在 UNIX 下面,要把 32-bit 程式 porting 到 64-bit 可能要比 Windows 多花費多一點功夫。
兩個型別問題影響著程式的相容性:
  1. 在 UNIX 下面,long 的大小在 32-bit 與 64-bit 的系統下是不一樣的
  2. 同樣是 64-bit 系統,UNIX 與 Windows 對於 long 的大小看法是不一致的
為了使程式在 32-bit 與 64-bit 之間以及 UNIX 與 Windows 之間的相容性提昇,改用固定長度的資料型態是寫程式的一個好習慣
在 UNIX 下面,我們可以改用 stdint.h 這個 header file 中對於資料型態的定義:
int8_t     8-bit signed interger
int16_t    16-bit signed interger
int32_t    32-bit signed interger
int64_t    64-bit signed interger
uint8_t    8-bit unsigned interger
uint16_t   16-bit unsigned interger
uint32_t   32-bit unsigned interger
uint64_t   64-bit unsigned interger
在 Windows 下面,則改用下面這些整數固定大小的資料型態
INT8       8-bit signed integer
INT16      16-bit signed integer
INT32      32-bit signed integer
INT64      64-bit signed integer
UINT8      8-bit unsigned integer
UINT16     16-bit unsigned integer
UINT32     32-bit unsigned integer
UINT64     64-bit unsigned integer
絕對不要再使用 int 和 long !請愛用stdint.h內的型別
尤其是寫網路程式時,作業系統與作業系統的位元數所造成的型別相容性問題
參考資料:
  1. Wikipedia: 64-bit data models
  2. 64-Bit Programming Models: Why LP64?
  3. Introduction to Win32/Win64
  4. Porting 32-bit Applications to the Itanium® Architecture
  5. Preparing Code for the IA-64 Architecture (PDF)

2013年7月27日 星期六

python自然語言教學 nltk課程

參考資料:http://ccl.pku.edu.cn/alcourse/nlp/

課程名稱:自然語言處理導論課程討論區 ( 最新貼:2010-6-16 9:21:04 )
任課教師:詹衛東 *  劉揚王厚峰常寶寶*** 北京大學中文系** 北京大學信息科學技術學院
電子郵件:zwd@pku.edu.cn (詹卫东)liuyang@pku.edu.cn(劉揚)
辦公電話:6276581062765835-205(分機)
有關本課程的任何問題和建議,都歡迎與我們聯繫
2011-2012學年第二學期上課時間:2012年2月13日~6月8日( 5~6節地點:教206考試時間
教學參考資料
史蒂芬鳥,伊万·克萊因和愛德華·洛珀。2009年與Python自然語言處理。O'Reilly Media出版。
克里斯托弗D.萬寧和辛里奇SCHUTZE的的。1999年統計自然語言處理的基礎。麻省理工學院出版社。
丹尼爾Jurafsky和詹姆斯·馬丁。2000年語音和語言處理。培生教育。
課程進度安排                 

 
序號 內容提要 講義參考資料
第1週
2012年2月13日
課程概述:課程安排, 參考文獻說明, 等等.
緒論:什麼是自然語言處理?
課程安排 问答系统:ElizaIBM Watson,……
機器翻譯系統:GoogleWorldLingo,……
自然語言處理的支撐科學是什麼?(Author:Shuly Wintner)
漫話人工智能 (顧森)
 
第2週
2012年2月20日
理論基礎:
中文文本的自動分詞
第02章漢語自動分詞研究述評
 
第3週
2012.2.27
理論基礎:
詞性標註方法
Chapter_03 
 
楊孝華二卷
 
第4週
2012年3月5日
理論基礎:
漢語的句法結構分析(上)
Chapter_04(I)
簡單句法分析方法示例
(自底向上,自頂向下,左角分析法)
 
歐萊的分析算法
第5週
2012.3.12
理論基礎:
漢語的句法結構分析(下)
chapter_04(II)
 
句法結構歧義的程度
第6週
2012.3.19
理論基礎:
語義分析
 
Chapter_05 
第7週2012.3.26
 
理論基礎:
語篇分析(王厚峰)
Chapter_06
 
第8週
2012.4.2
討論課(第一次大作業)
作業要求:
 
 
  • 根據選課人數情況,採用分組報告形式在課堂上進行交流。
  • 所有選課同學均需提交書面報告。
  • 報告文件名 ​​請採用統一格式:
     學號_姓名_文章名.doc/pdf
  • 可以合作完成,但人數不得超過3人。合作完成的報告,要詳細註明各人的分工情況。
  • 作業電子版(word或pdf文件)發至 zwd@pku.edu.cn
  • 請在2012.4.16(含)之前提交作業。如果需要延期提交,請給出理由。但不應晚於4.23日提交。晚於4.23日提交的作業將罰分。
第9週
2012年4月9日
工程實踐:
Python及NLTK包的應用—— 訪問語言資源
教材下載:NLP與Python
Chapter_07
要求:熟悉教材第1章第1、2、3、4節;熟悉教材第2章第2、3節,了解第1、4節。
蟒蛇-2.5.4
第10週
2012年4月16日
工程實踐:
Python及NLTK包的應用—— 文本處理基礎
Chapter_08
要求:熟悉教材第3章第1、2、8、9節,了解第3、4、5、6、7節。
第11週
2012年4月23日
工程實踐:
Python及NLTK包的應用—— 程序設計進階
Chapter_09
要求:熟悉教材第4章1、2、3、4節,了解第5、6節。
第12週
2012.4.30
工程實踐:
Python及NLTK包的應用—— 分詞和詞性標註
Chapter_10
要求:熟悉教材第5章第1、2、3節,了解第4、5節。
第13週
2012.5.7
工程實踐:
Python及NLTK包的應用—— 句法分析實現
Chapter_11
要求:了解教材第8章第1、2、3、4節。[特別說明,期末考試第8章第1、2、3、4節不作要求]
第14週
2012年5月14日
工程實踐:
Python及NLTK包的應用—— 信息抽取
Chapter_12
要求:熟悉教材第7章第1、2、3、4、5、6節。
第15週
2012.5.21
工程實踐:
Python及NLTK包的應用—— 文本分類
Chapter_13
要求:熟悉教材第6章第1、2、3節,了解第4、5、6節。[特別說明,期末考試第6章第4、5、6節不作要求]
第16週
2012年5月28日
機器翻譯(常寶寶)
  
第17週
2012年6月4日
 
討論課 (第二次大作業)
漢語自動分詞與詞性標註
 
 
  • 根據選課人數情況,採用分組報告形式在課堂上進行交流。
  • 所有選課同學均需提交書面報告。
  • 可以合作完成,但人數不得超過3人。合作完成的報告,要詳細註明各人的分工情況。
  • 在6月11日(個別情況需要延期,須給出理由,但不遲於6月25日)前,請將所有程序源碼、數據文件及實驗報告(限pdf格式)打包壓縮為“學號_姓名.rar”,將其作為附件發送至liuyang@pku.edu.cn(我收到後會有回复,注意確認)。
第18週
2012.6.11 
考試