Python自然语言处理 3 处理原始文本
本章的目的是要回答下列問(wèn)題:
(1) 怎樣才能編寫程序訪問(wèn)本地和網(wǎng)絡(luò)上的文件,從而獲得無(wú)限的語(yǔ)言材料?
(2)如何把文檔分割成單獨(dú)的單詞和標(biāo)點(diǎn)符號(hào),并進(jìn)行文本語(yǔ)料上分析?
(3)怎樣編寫程序產(chǎn)生格式化的輸出,并把結(jié)果保存在文件中?
為了解決這些問(wèn)題,本章將介紹NLP的重要概念,包括分詞和詞干提取.在過(guò)程中,鞏固Python知識(shí)并且學(xué)習(xí)關(guān)于字符串,文件和正則表達(dá)式的知識(shí).網(wǎng)絡(luò)上的文本都是HTML格式的,我們將學(xué)習(xí)如何使用HTML
一,從網(wǎng)絡(luò)和硬盤訪問(wèn)文本
#處理電子書 txt
古騰堡項(xiàng)目http://www.gutenberg.org/catalog/有25000本免費(fèi)在線書籍的目錄
編號(hào)2554的文本是<罪與罰>
from urllib import urlopen
url = "http://www.gutenberg.org/files/2554/2554-0.txt"
raw = urlopen(url).read()
type(raw)
'The Project Gutenberg EBook of Crime and Punishment, by Fyodor Dostoevsky\r\n\' 分詞
import nltk
import sys
reload(sys)
sys.setdefaultencoding( "utf-8" )
tokens = nltk.word_tokenize(raw)
type(tokens)
244761 tokens[:15] ['\xef','\xbb','\xbfThe','Project','Gutenberg' 在鏈表中創(chuàng)建NLTK文本
text = nltk.Text(tokens)
type(text)
text[1020:1060]
text.collocations()
raw.find("PART I")
5381 raw.rfind("End of Project Gutenberg’s Crime")1182515 raw = raw[5381:1182515]
raw.find("PART I")
0
#處理HTML
url = "http://news.bbc.co.uk/2/hi/health/2284783.stm"
html = urlopen(url).read()
html[:60]
from bs4 import BeautifulSoup
soup = BeautifulSoup(html, 'html.parser')
raw = soup.get_text()
tokens = nltk.word_tokenize(raw)
tokens
#處理搜索引擎的結(jié)果
網(wǎng)絡(luò)可以被看做未經(jīng)標(biāo)注的巨大語(yǔ)料庫(kù)
#處理RSS訂閱
http://feedparser.org
#讀取本地文件
import sys
#從PDF,MS word及其他二進(jìn)制格式中提取文本
使用pypdf和pywin32
#捕獲用戶輸入
s = raw_input("Enter some text: ")
#NLP的流程
二, 字符串: 最底層的文本處理
#鏈表與字符串的差異
字符串和鏈表都是一種序列.可以通過(guò)索引抽取它們中的一部分,可以給它們切片,也可以使用連接將它們合并在一起,但是,字符串和鏈表之間不能連接
query = 'Who knows?'?
beatles = ['John', 'Paul', 'George', 'Ringo']
query[0] = 'F'? #不可變
beatles[0] = 'F' #可變的
三, 使用Unicode進(jìn)行文字處理
#從文件中提取已編碼文本
import? ?codecs
f = codecs.open(path, encoding='utf8')
四? 使用正則表達(dá)式檢測(cè)詞組搭配
五 正則表達(dá)式的有益應(yīng)用
#提取字符塊
找出文本中兩個(gè)或兩個(gè)以上的元音序列,并確定它們的相對(duì)頻率
import re wsj = sorted(set(nltk.corpus.treebank.words())) fd = nltk.FreqDist(vs for word in wsj for vs in re.findall(r'[aeiou]{2,}', word)) fd.items()#在字符塊上做更多事情
#查找詞干
查詢"laptops"會(huì)找到含有"laptop"的文檔
def stem(word):
? ? for suffix in ['ing','ly','ed','ious','ies','ive','es','s','ment']:
? ? ? ? if word.endswith(suffix):
? ? ? ? ? ? return word[:-len(suffix)]
? ? return word
使用正則表達(dá)式
#搜索已分詞文本
這種自動(dòng)和人工處理相結(jié)合的方式是最常見(jiàn)的建造新語(yǔ)料庫(kù)的方式
六 規(guī)范化文本
raw = """DENNIS:Listen, strange women lying in ponds distributing swords is no basis for a system of government. Supreme executive power derives from a mandate from the masses, not from some farcical aquatic ceremony."""
tokens = nltk.word_tokenize(raw)
#詞干提取器
porter = nltk.PorterStemmer() lancaster = nltk.LancasterStemmer() [porter.stem(t) for t in tokens] [u'denni',':','listen',',',u'strang',#詞形歸并 wnl = nltk.WordNetLemmatizer() [wnl.lemmatize(t) for t in tokens] ['DENNIS',':','Listen',',','strange',u'woman','lying',
七 用正則表達(dá)式為文本分詞
#分詞的簡(jiǎn)單方法
re.split(r" ', raw)? ? #在空格符處分割原始文本
re.split(r'[ \t\n]+', raw)? #同時(shí)需要匹配任何數(shù)量的空格符\制表符或換行符
八 分割
#斷句
sent_tokenizer = nltk.data.load('tokenizers/punkt/english.pickle') text = nltk.corpus.gutenberg.raw('chesterton-thursday.txt') sents = sent_tokenizer.tokenize(text) pprint.pprint(sents[171:181])#分詞
九 格式化:從鏈表到字符串
#從鏈表到字符串
silly = ['We','called','him','Tortoise','because','he','taught','us','.'] ' '.join(silly) 'We called him Tortoise because he taught us .' ';'.join(silly) 'We;called;him;Tortoise;because;he;taught;us;.' ''.join(silly) 'WecalledhimTortoisebecausehetaughtus.'十 深入閱讀
總結(jié)
以上是生活随笔為你收集整理的Python自然语言处理 3 处理原始文本的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 无人职守安装 XP
- 下一篇: You may need an appr