研究的问题
- 为了获得无限范围的语言材料我们如何编写程序来从本地文件和Web中访问文本?
- 我们如何将文档分割成单独的单词和标点符号,
所以我们可以进行和前几章一样的文本语料库分析?
3.我们如何编写程序来生成格式化的输出并将其保存在文件中?
从Web和磁盘访问文本
1.电子图书
1) raw text获取和类型处理
1.从Gutenberg读取txt文件(太大读不出来,读本地的代替了,读出是字符串类型)
from urllib.request import urlopen
url = "http://www.gutenberg.org/files/2554/2554.txt"
raw = urlopen(url).read()
raw=open("./text.txt").read()
2.把读出的内容进行 tokenization(去掉空格,空行,换行的过程),成了List类型
tokens = nltk.word_tokenize(raw)
3.把tokenization后的List化为text类型
text = nltk.Text(tokens)
2)text一些操作
1.输出文本中搭配使用的词
text.collocations()
2.找某字符串开始出现的位置
raw.find("PART I")
3.找某字符串开始结束的位置
raw.rfind("PART I")
4.使用find() rfind()可以截取包含某字符串的那段
2.处理HTML
1) HTML获取和类型处理
1.读取html文件(同text一样)
html=open("./html.html").read()
2.把html文件转换为raw text(python3需要安装BS4)
from bs4 import BeautifulSoup
raw = BeautifulSoup(html,"html5lib").get_text()
3.其余操作同raw text一样处理
3.处理搜索引擎结果
搜索引擎语料库优点
1)规模大 2)易使用
搜索引擎语料库缺点
1)搜索模式严格受限,搜索引擎通常只允许搜索单个单词或单词字符串,有时使用通配符。
2)搜索引擎给出的结果不一致
3)最后,搜索引擎返回的结果中的标记可能会发生不可预测的变化,从而破坏任何基于模式的定位特定内容的方法(使用搜索引擎api可以改善这个问题)。
4.处理 RSS Feeds
博客圈是一个重要的文本来源,通过Universal Feed Parser可以任意下载里面的内容
1) blog 获取和类型处理
需要安装feedparser
import feedparser
llog = feedparser.parse("http://languagelog.ldc.upenn.edu/nll/?feed=atom")
nltk.word_tokenize(BeautifulSoup(llog.entries[2].content[0].value,"html5lib").get_text())
2)blog 一些操作
llog['feed']['title']
post = llog.entries[2]
post.title
content = post.content[0].value
5.读取本地文件
1) 本地文件获取
import os
os.listdir('.')
path = nltk.data.find('corpora/gutenberg/melville-moby_dick.txt')
raw = open(path, 'rU').read()
6.从PDF、MSWord和其他二进制格式中提取文本
PDF和msword,只能使用专门的软件打开,第三方库(如pypdf和pywin32)提供了对这些格式的访问,从多文档中提取文本尤其具有挑战性。对于经过一次性转换个别文件,使用合适的应用程序打开文档,然后将其作为文本保存到本地就可以访问它。如果文档已经在Web上,您可以在谷歌的搜索框中输入它的URL。
搜索结果通常包含一个指向HTML文档的链接,您可以将其保存为文本。
7.捕获用户的输入
s = input("Enter some text: ")
print ("You typed", len(nltk.word_tokenize(s)), "words.")