- 簽證留學(xué) |
- 筆譯 |
- 口譯
- 求職 |
- 日/韓語 |
- 德語
接下來要搜索一支名為RIMM的股票:
>>> lotsOtweets = fpGrowth.getLotsOfTweets('RIMM')
fetching page 1
fetching page 2
lotsotweets列表包含14個子列表,每個子列表有100條推文??梢暂斎胂旅娴拿顏聿榭赐莆牡膬?nèi)容:
>>> lotsOtweets [0][4] .text
u"RIM: Open The Network, Says ThinkEquity: In addition, RIMM needs to reinvent its image, not only demonstrating ... http://bit.ly/lvlVlU"
正如所看到的那樣,有些人會在推文中放人URL。這樣在解析時,結(jié)果就會比較亂。因此必須去掉URL,以便可以獲得推文中的單詞。下面程序清單中的一部分代碼用來將推文解析成字符串列表,另一部分會在數(shù)據(jù)集上運(yùn)行FP-growth算法。將下面的代碼添加到fpGrowth.py文件中。
程序清單2 文本解析及合成代碼
上述程序清單中的第一個函數(shù)里添加了一行代碼用于去除URL。這里通過調(diào)用正則表達(dá)式模塊來移除任何URL。程序清單2中的另一個函數(shù)mineTweets()為每個推文調(diào)用textParse。最后,mineTweets()函數(shù)將命令封裝到一起,來構(gòu)建FP樹并對其進(jìn)行挖掘。最后返回所有頻繁項(xiàng)集組成的列表。
下面看看運(yùn)行的效果:
>>> reload(fpGrowth)
<module 'fpGrowth' from 'fpGrowth.py'>
Let's look for sets that occur more than 20 times:
>>> listOfTerms = fpGrowth.mineTweets(lotsOtweets, 20)
How many sets occurred in 20 or more of the documents?
>>> len(listOfTerms)
455
我寫這段代碼的前一天,一家以RIMM股票代碼進(jìn)行交易的公司開了一次電話會議,會議并沒有令投資人滿意。該股開盤價相對前一天封盤價暴跌22%。下面看下上述情況是否在推文中體現(xiàn):
>>> for t in listOfTerms:
... print t
set ([u'rimm', u'day'])
set ([u'rimm', u'earnings'])
set ([u'pounding', u'value'])
set ([u'pounding', u'overnight'])
set ([u'pounding', u'drops'])
set ([u'pounding', u'shares'])
set ([u'pounding', u'are'])
set ([u'overnight'])
set ([u'drops', u'overnight'])
set ([u'motion', u'drops', u'overnight'])
set ([u'motion', u'drops', u'overnight', u'value'])
set ([u'drops', u'overnight', u'research'])
set ([u'drops', u'overnight', u'value', u'research'])
set ([u'motion', u'drops', u'overnight', u'value', u'research'])
set ([u'motion', u'drops', u'overnight', u'research'])
set ([u'drops', u'overnight'; u'value'])
嘗試一些其他的minSupport值或者搜索詞也是蠻有趣的。
我們還記得FP樹的構(gòu)建是通過每次應(yīng)用一個實(shí)例的方式來完成的。這里假設(shè)已經(jīng)獲得了所有數(shù)據(jù),所以剛才是直接遍歷所有的數(shù)據(jù)來構(gòu)建Fp樹的。實(shí)際上可以重寫createTree()函數(shù),每次讀人一個實(shí)例,并隨著Twitter流的不斷輸入而不斷增長樹。FP-growth算法還有一個map-reduce版本的實(shí)現(xiàn),它也很不錯,可以擴(kuò)展到多臺機(jī)器上運(yùn)行。Google使用該算法通過遍歷大量文本來發(fā)現(xiàn)頻繁共現(xiàn)詞,其做法和我們剛才介紹的例子非常類似。
責(zé)任編輯:admin