文本的最重要来源无疑是网络。探索现成的文本集合是很方便的,然而每个人都有自己的文本来源,需要学习如何去访问他们。
首先,我们要学习从网络和硬盘访问文本。
1.电子书
NLTk语料库集合中存有古腾堡项目的一小部分样例文本,如果你对古腾堡项目其他的文本感兴趣,可以在http://www.gutenberg.org/catalog/上浏览其他书籍
下面以编号2554的文本《罪与罚》为例,简单介绍怎么通过Python访问
-*- encoding:utf-8 -*- from urllib.request import urlopen import nltk url=r'http://www.gutenberg.org/files/2554/2554.txt' raw=str(urlopen(url).read(),encoding='utf-8') print(type(raw))
此时输出为<class 'str'>
>>>print(raw[:75]) The Project Gutenberg EBook of Crime and Punishment, by Fyodor Dostoevsky
>>>print(len(raw))
1176831
变量raw包含了1176831个字符,这是这本书的原始内容,但是其中有很多我们不关系的细节,例如空格,换行符等等。对于语言处理,要将字符串分解为词和标点符号,这一过程我们成为分词,用于产生词汇和标点符号的列表。
>>>token=nltk.word_tokenize(raw) >>>print(type(token)) <class 'list'> >>>print(len(token)) 254352 >>>print(token[:10]) ['The', 'Project', 'Gutenberg', 'EBook', 'of', 'Crime', 'and', 'Punishment', ',', 'by']
请注意,NLTK需要分词,但之前打开的URL读入字符串任务都没有进行分词。如果进一步在链表中创建NLTK文本,便可以进行一些常规的链表操作,例如切片
>>>text=nltk.Text(token) >>>print(text[1020:1060]) ['AND', 'PUNISHMENT', 'PART', 'I', '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.'] >>>print(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
下面我们介绍find和rfind函数
例如,古腾堡项目下载的文本都包含一个首部,里面有文本的名称、作者等等。因此在原始文本中挑选内容之前,需要手工检查文件来发现标记内容开始和结尾的特定字符串。
>>>start=raw.find('PART I') >>>end=raw.rfind("End of Project Gutenberg's Crime" ) >>>raw=raw[start:end] >>>print(raw.find('PART I')) 0
函数find()和rfind()(反向的find)用于获取字符串切片所在的索引值。
2.处理HTML
网络上的本文大多是HTML文件格式的,可以直接使用Python将文本获取下来。这里主要利用了Python的urllib库,经常写爬虫的对这个库应该非常的熟悉。
我们在这里挑选了一个BBC新闻“Blonds to die out in 200 years”进行处理。
下面写一个最简单的py爬虫将数据爬到本地:
>>>from urllib.request import urlopen >>>url=r'http://news.bbc.co.uk/2/hi/health/2284783.stm' >>>html=str(urlopen(url).read(),encoding='utf-8') >>>print(html[:60]) <!doctype html public "-//W3C//DTD HTML 4.0 Transitional//EN
我们看到该网页的文本已经被我们爬到了,这时候输入print(html)就可以看到所有的内容,包括元标签,表单,表格等等。
在原书中提供了一个nltk.clean_html()函数,但是这个函数已经过时了,现在我们会使用BeautifulSoup库来代替。
例如,课后习题第20题:编写代码来访问喜爱的网页,并从中提取一些文字。例如,访问一个天气网,提取你所在的城市的温度。现在我们以上海市为例,获取上海当天的温度情况。代码如下:
from bs4 import BeautifulSoup from urllib.request import urlopen def tem(http): htbyte=urlopen(http).read() ###爬取网站 html=htbyte.decode('utf-8') soup=BeautifulSoup(html,'lxml') ##使用BeautifulSoup ul=soup.find('ul',attrs={'class':'t clearfix'}) soup_tem=BeautifulSoup(str(ul),'lxml') tem=soup.find('p',attrs={'class':'tem'}) text=tem.get_text() print('上海市今日温度:',text) http=r'http://www.weather.com.cn/weather/101020100.shtml' tem(http)
输出结果为:上海市今日温度: 19℃
关于更多爬虫,需要自己多练习。。
3.处理RSS订阅
博客圈是文本的重要来源,在处理RSS订阅时Python有一个第三方库叫做Universal Feed Parser(点击下载)。在这个库的帮助下我们可以轻松访问博客的内容。
>>>import feedparser >>>llog=feedparser.parse('http://languagelog.ldc.upenn.edu/nll/?feed=atom') >>>print(llog['feed']['title'])
Language Log >>>print(len(llog.entries))
13 >>>post=llog.entries[2]
>>>print(post.title)
The Donald's THE, again
>>>print(content[:70])
<blockquote class="twitter-tweet"><p dir="ltr" lang="en">THE African A
4.读取本地文件:open()函数,基础。PDF文件:pypdf库
5.NLP流程