3.NLTK之加工原料文本

来源:互联网 发布:淘宝宝贝详情模板制作 编辑:程序博客网 时间:2024/04/23 22:33

从网络和硬盘访问文本
电子书
编号 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; AvdotyaRomanovna; Rodion Romanovitch; Marfa Petrovna; Sofya Semyonovna; oldwoman; 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 nextblonde hair is caused by a recessive gene . In order for a child to have blondhave blonde hair , it must have the gene on both sides of the family in the gere is a disadvantage of having that gene or by chance . They do n't disappeardes 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 使用正则表达式检测词组搭配
见正则表达式

1 0