主要解决三个问题:
1.访问本地或者网络上的文件
2.分割成单独的词和标点符号
3.产生格式化输出
from __future__ import division
import nltk, re, pprint
一、从网络和硬盘访问文本
from urllib.request import urlopen#python3与python2的库位置不同
url = r'http://www.gutenberg.org/files/24272/24272-0.txt'
raw = urlopen(url).read()
raw = raw.decode('utf-8')
len(raw)
分词
tokens = nltk.word_tokenize(raw)
type(tokens)
text=nltk.Text(tokens)
type(text)
raw.find("THE MOUNTAIN OF FEARS")
raw.rfind("our email newsletter to hear about new eBooks")
raw = raw[1005:309111]
raw.find("THE MOUNTAIN OF FEARS")
利用find 和rfind函数重新定位文本内容
二、处理的HTML
from bs4 import BeautifulSoup
url="http://news.bbc.co.uk/2/hi/health/2284783.stm"
html=urlopen(url).read()
raw = BeautifulSoup(html,'lxml').get_text()#从html中提取文本
tokens = nltk.word_tokenize(raw)
tokens = tokens[96:399]
text = nltk.Text(tokens)
text.concordance('gene')
三、读取本地文件
f=open('C:\\Users\\Yafang\\Desktop\\doc.txt')
print(f.read())
for line in f:
print(line.strip())#strip()方法删除输入行结尾的换行符
捕获用户输入
s=input("Enter some text:")
四、字符串:最底层的文本处理
cirus = 'monty python\'s flying circus'#转义字符
couplet = "shall i compare"\
"thou are more"#斜杠表示还未输入完成
couplet = """you
are
very
good"""#三引号实现多行输入
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.keys()
字符串不可变,链表可变
将文本翻译成unicode叫做解码,将unicode转化为其他编码叫做编码
五、使用unicode进行文字处理
1.codecs模块提供了将编码数据读入为unicode字符串和将unicode字符串编码形式写出的函数,codecs.open()函数有一个encoding参数来指定被读取或写入的文件的编码。
path = nltk.data.find('corpora/unicode_samples/polish-lat2.txt')
import codecs
f=codecs.open(path,encoding='latin2')
ord('a')#查找一个字符的整数序数
a=u'\u0061'
如果希望能够在一个python文件中使用自己的字符串输入及编辑的标准方法,需要在文件的第一行或第二行中包含字符串:
# -*- coding:<coding>-*-
六、使用正则表达式检测词组搭配
在python中使用正则表达式,需要使用re函数库,还需要用于搜索的词汇链表
import re
wordlist=[w for w in nltk.corpus.words.words('en') if w.islower()]
分词:
1、用空格分隔文本
raw = """when i'm a duchess, she said to herself,
(not in a very hopeful tone), i won't have any pepper in my kitchen"""
re.split(r' ',raw)
2、匹配任何数量的空格符、制表符、换行符
re.split(r'[ \t\n]+',raw)
re.split(r'\s+',raw)
七、写回文件
output_file = open('C:\\Users\\Yafang\\Desktop\\doc.txt','w')
words = set(nltk.corpus.genesis.words('english-kjv.txt'))
for word in sorted(words):
output_file.write(word + "\n")