最近在看《Python自然語言處理》中文版這本書,可能由於是從py2.x到py3.x,加上nltk的更新的原因,或者作者的一些筆誤,在書中很多代碼都運行不能通過,下面我就整理一下一點有問題的代碼。
第一章:
p3.該處為小建議,書中沒有錯誤:關於nltk.book的下載,最好下載到'/nltk_data'文件夾下,如'D:/nltk_data'
p7.text3.generate(). generate()函數用法已經過時,正在查找最新的方法。
p18.關於FreqDist()函數發生了更新,如果按照書上的代碼鍵入,並不會得到預期的結果,可以用下面的方法進行改進來得到相同的結果:
>>>fdist1=FreqDist(text1) >>>len(fdist1) 19317 >>>vocabulary1=sorted(fdist1.items(),key=lambda jj:jj[1],reverse=True) >>>s=[] >>>for i in range(len(vocabulary1)): s.append(vocabulary1[i][0]) >>>print(s)
p22.FreqDist函數,和18頁的問題是一樣的,可以仿照上面的解決方法進行改進。
p32.babelize_shell() 該函數在nltk3.0中已經不再可用了,跳過該函數講解部分。
第二章:
p48頁:cfd=nltk.ConditionalFreqDist((target,file[:4]) for fileid in inaugural.fileids() for w in inaugural.words(fileid) for target in ['america','citizen'] if w.lower().startswith(target)) 會顯示出錯
改正:將第一個括號內的file[:4]改為fileid[:4]即可。即:cfd=nltk.ConditionalFreqDist((target,fileid[:4]) for fileid in inaugural.fileids() for w in inaugural.words(fileid) for target in ['america','citizen'] if w.lower().startswith(target))
p51:代碼最后一行cfd.plot(cumulative=True少了閉括號。
p56:>>>cfd 書上寫的是不顯示cfd里面的內容,而在Python3.X中,輸入這句話會自動輸出cfd里面的內容。
p58:使用雙連詞生成隨機文本。輸入nltk.bigrams(sent)並不會生成列表,需要寫成:list(nltk.bigrams(sent))才能生成書上的形式。
p72:倒數第二行,>>>wn.synset('car.n.01').lemma_names忘記加括號,改為:>>>wn.synset('car.n.01').lemma_names()
p73:一開始的代碼.definition和.examples和上面問題一樣,需要加括號才能顯示結果。本頁上的其他函數也需要同樣處理、
P85:如果使用py3,在使用urlopen時需要:from urllib.request import urlopen
P87:NLTK提供了輔助函數nltk.clean_html()這個函數現在不在支持,可以使用beautifulsoup庫。
P116:在concordanc函數中,wc=width/4,在py3中會報錯,應該改為wc=width//4.
P121:關於nltk.regexp_tokenize(text,pattern)並不會得到預期的效果,需要對pattern進行重寫,具體重寫代碼如下:
pattern = r"""(?x) # set flag to allow verbose regexps (?:[A-Z]\.)+ # abbreviations, e.g. U.S.A. |\d+(?:\.\d+)?%? # numbers, incl. currency and percentages |\w+(?:[-']\w+)* # words w/ optional internal hyphens/apostrophe |\.\.\. # ellipsis |(?:[.,;"'?():-_`]) # special characters with meanings """
重寫以后在執行就會出現預期的結果。
由於是剛開始看,所以后面的還沒看到,本文也會持續更新新遇到的錯誤,也歡迎大家補充。