3.NLTK之加工原料文本

從網絡和硬盤訪問文本
電子書
編號 2554 的文本是《罪與罰》的英文翻譯,我們可以如下方式訪問它。

>>> from urllib import request
>>> url = "http://www.gutenberg.org/files/2554/2554.txt"
>>> response = request.urlopen(url)
>>> raw = response.read().decode('utf8')
>>> type(raw)
<class 'str'>
>>> len(raw)
1176893
>>> raw[:75]
'The Project Gutenberg EBook of Crime and Punishment, by Fyodor Dostoevsky\r\n'

變量raw是這本書原始的內容,包括很多我們不感興趣的細節,如空格、換行符和空
行。請注意,文件中行尾的\r 和\n,這是 Python 用來顯示特殊的回車和換行字符的方式(這
個文件一定是在 Windows 機器上創建的)。我們要對其進行分詞操作,產生一個詞彙和標點符號的鏈表。

>>> tokens = nltk.word_tokenize(raw)
>>> type(tokens)
<class 'list'>
>>> len(tokens)
254354
>>> tokens[:10]
['The', 'Project', 'Gutenberg', 'EBook', 'of', 'Crime', 'and', 'Punishment', ',', 'by']

如果我們現在採取進一步的步驟從這個鏈表創建一個 NLTK 文本,我們可以進行我
們在第 1 章看到的所有的其他語言的處理,也包括常規的鏈表操作,例如切片:

>>> text = nltk.Text(tokens)
>>> type(text)
<class 'nltk.text.Text'>
>>> text[1024:1062]
['CHAPTER', 'I', 'On', 'an', 'exceptionally', 'hot', 'evening', 'early', 'in',
 'July', 'a', 'young', 'man', 'came', 'out', 'of', 'the', 'garret', 'in',
 'which', 'he', 'lodged', 'in', 'S.', 'Place', 'and', 'walked', 'slowly',
 ',', 'as', 'though', 'in', 'hesitation', ',', 'towards', 'K.', 'bridge', '.']
>>> text.collocations()
Katerina Ivanovna; Pyotr Petrovitch; Pulcheria Alexandrovna; Avdotya
Romanovna; Rodion Romanovitch; Marfa Petrovna; Sofya Semyonovna; old
woman; Project Gutenberg-tm; Porfiry Petrovitch; Amalia Ivanovna;
great deal; Nikodim Fomitch; young man; Ilya Petrovitch; n't know;
Project Gutenberg; Dmitri Prokofitch; Andrey Semyonovitch; Hay Market



處理HTML
網絡上的文本大部分是 HTML 文件的形式。 HTML 的全部內容包括: meta 元標籤、圖像標籤、map 標
籤、JavaScript、表單和表格。

>>> url = "http://news.bbc.co.uk/2/hi/health/2284783.stm"
>>> html = request.urlopen(url).read().decode('utf8')
>>> html[:60]
'<!doctype html public "-//W3C//DTD HTML 4.0 Transitional//EN'

我們使用BeautifulSoup來從HTML中提取文本,然後我們可以對原始文本進行分詞:

>>> from bs4 import BeautifulSoup
>>> raw = BeautifulSoup(html).get_text()
>>> tokens = nltk.word_tokenize(raw)
>>> tokens
['BBC', 'NEWS', '|', 'Health', '|', 'Blondes', "'to", 'die', 'out', ...]

你可以選擇你感興趣的標識符,按照前面講的那樣初始化一個文本。

>>> tokens = tokens[110:390]
>>> text = nltk.Text(tokens)
>>> text.concordance('gene')
Displaying 5 of 5 matches:
hey say too few people now carry the gene for blondes to last beyond the next
blonde hair is caused by a recessive gene . In order for a child to have blond
have blonde hair , it must have the gene on both sides of the family in the g
ere is a disadvantage of having that gene or by chance . They do n't disappear
des would disappear is if having the gene was a disadvantage and I do not thin

訪問單個字符
我們可以計數單個字符。通過將所有字符小寫來忽略大小寫的區分,並過濾掉非字母字符。

>>> from nltk.corpus import gutenberg
>>> raw = gutenberg.raw('melville-moby_dick.txt')
>>> fdist = nltk.FreqDist(ch.lower() for ch in raw if ch.isalpha())
>>> fdist.most_common(5)
[('e', 117092), ('t', 87996), ('a', 77916), ('o', 69326), ('n', 65617)]
>>> [char for (char, count) in fdist.most_common()]
['e', 't', 'a', 'o', 'n', 'i', 's', 'h', 'r', 'l', 'd', 'u', 'm', 'c', 'w','f', 'g', 'p', 'b', 'y', 'v', 'k', 'q', 'j', 'x', 'z']
>>> fdist.plot()

plot

* 3.3 使用 Unicode 進行文字處理*
Unicode支持超過一百萬種字符。每個字符分配一個編號,稱爲 編碼點。在 Python 中 ,編碼點寫作\uXXXX 的形式,其中 XXXX是四位十六進制形式數。
解碼:將文本翻譯成Unicode;
編碼:將Unicode 轉化爲其它編碼的過程;
Uni
從 Unicode的角度來看,字符是可以實現一個或多個 字形的抽象的實體。只有字形可以出現在屏幕上或被打印在紙上。一個字體是一個字符到字形映射。

從文件中提取已編碼文本
假設我們有一個小的文本文件,我們知道它是如何編碼的。例如:polish-lat2.txt 顧名思義是波蘭語的文本片段(來源波蘭語 Wikipedia;可以在 http://pl.wikipedia.org/wiki/Biblioteka_Pruska中看到)。此文件是 Latin-2 編碼的,也稱爲 ISO-8859-2。nltk.data.find()函數爲我們定位文件。

>>> path = nltk.data.find('corpora/unicode_samples/polish-lat2.txt')

codecs模塊:提供了將編碼數據讀入爲Unicode 字符串和將Unicode 字符串以編碼形式寫出的函數。
codecs.open()函數:encoding 參數來指定被讀取或寫入的文件的編碼。

>>> f = open(path, encoding='latin2')
>>> for line in f:
...    line = line.strip()
...    print(line)
Pruska Biblioteka Państwowa. Jej dawne zbiory znane pod nazwą
"Berlinka" to skarb kultury i sztuki niemieckiej. Przewiezione przez Niemców pod koniec II wojny światowej na Dolny Śląsk, zostały odnalezione po 1945 r. na terytorium Polski. Trafiły do Biblioteki Jagiellońskiej w Krakowie, obejmują ponad 500 tys. zabytkowych archiwaliów, m.in. manuskrypty Goethego, Mozarta, Beethovena, Bacha.

3.4 使用正則表達式檢測詞組搭配
正則表達式

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章