python自然语言处理第三章:处理原始文本
from urllib import urlopen
url="http://www.gu tenberg.org/files/2554/2554.txt"
raw=urlopen(url).read()
type(raw)
proxies={'http:'http://www.xomeproxy.com:3128'}
raw=urlopen(url,prxies=proxies).read()
tokens=nltk.word_tokensize(raw)
type(tokens) #list
3.find()方法和rfind()方法(反向索引)raw.find("PART I")
raw.rfind("PART I")
4.從HTML中提取文本。url="http://news.bbc.co.uk/2/hi/health/2284783.stm"
html=urlopen(url).read()
html[:60]
NLTK中的輔助函數nltk.clean_htm()將HTML字符串作為參數,返回原始文本。然后對原始文本進行分詞。raw=nltk.clean_html(html) #得到HTML原始文本
tokens=nltk.word_tokensize(raw) #分詞,得到詞匯鏈表
text=nltk.Text(tokens) #詞匯鏈表->文本
>>>import feedparser
>>>llog=feedparser.parser("http://languagelog.ldc.upeenn.edu/nll/?feed=atom")
>>>llog=['feed']['title']
u 'Language Log'
>>>len(llog.entries)
15
>>>post=llog.entries[2]
>>>post.title
u"He's My BF"
>>>content=post.content[0].value
>>>nltk.word_tokensize(nltk.clean_html(content))
>>>nltk.word_tokensize(nltk.clean(html(llog.entires[2].content[0].value))
6.讀取本地文件,讀取文件時要檢查目錄是否為當前目錄,不是則需要切換到目標目錄。f=open('document.txt') #open()函數的第二個參數表示打開方式,默認為‘rU’ r表示只讀,U表示通用
raw=f.read() #創建包含整個文本的字符串
方法二:
for line in f:
print line.strip() #刪除結尾的換行符
import os
os.listddir('.') 8.使用nltk.data.find()來獲取語料庫中項目的文件名,然后打開讀取它。
path=nltk.data.find('corpora/gutenberg/melville-moby_dict.txt')
raw=open(path,'rU').read()
>>>sent='colorless green ideas sleep furiously'
>>>for char in sent:r
>>> print char,
c o l o r l e s s g r e e n i d e a s s l e e p f u r i o u s l y
#計數單個字符
>>>from nltk.corpus import gutenberg
>>>raw=gutenberg.raw('melville-moby_dict.txt')
>>>fdist=nltk.FreqDist(ch.lower() for ch in raw if ch.isalpha())
>>>fdist.keys()
['e','t','a',o','n'..........]
10.正則表達式P109#查找以ed結尾的詞 r表示原始字符串
>>>import re
>>>[w for w in wordlist if re.search('ed$',w)]
#通配符. ^匹配字符串的開始,$匹配字符串的結尾
>>>[w for w in wordlist if re.search('^..j..t..$',w)]
#?是可選字符
>>>e-?mile #匹配email 和e-mail ?0個或1個
>>>sum(l for w in text if re.search('^e-mail$''w)) #計數文本中這個詞出現的總次數
#+表示一個或多個實例,*表示零個或多個實例 + and * 有時稱為ieKleene閉包或者閉包
>>>[w for w in wordlist if re.search('^m+i+e+$',w)]
#^出現在方括號中第一個時表示非
>>>[^aeiouAEOIU] # 匹配非元音字母
#\ 轉義 {} {3,5}重復3-5次,為前面的項目重復指定的次數 |或邏輯 ()表示操作符的范圍
11.正則表達式應用
#re.findall()找出所有匹配的指定正則表達式
>>>word='sdgoinkwenfoif;dvd'
>>>re.findall(r'[aeiou'],word)
#找出兩個或兩個以上元音序列,并確定他們的相對頻率
wdj=sorted(set(nltk.corpus.treebank.words()))
fd=nltk.FreqDist(vs for word in wsj
for vs in re.findall(r'[aeiou'],word))
fd.items()
#只匹配詞首的元音,詞尾的元音和詞的輔音.然后把匹配的詞連接起來
regexp=r'^[AEIOUaeiou]+|[AEIOUaeiou]+$[^AEIOUaeiou]'
def compress(word):
pieces=re.findall(regexp,word)
return ''.join(pieces)
english_udhr=nltk.corpus.udhr.words('Englis-Latin1')
print nltk.tokenwrap(compress(w) for w in english_udhr[:75])
#從羅托卡特語詞匯中提取所有的輔音-元音序列。
rotokas_words=nltk.corpus.toolbox.words('rotokas.dic')
cvs=[cv for w in rotokas_words for cv in re.findall(r'[ptksvr][aeiou]',w)]
cfd=nltk.ConditionalFreqDist(cvs)
cfd.tabulate()
def stem(word):
regexp=r'^(.*?)(ing|ly|ed|ious|ies|ive|es|s|ment)?$'
stem,suffix=re.findall(regexp,word)[0]
return stem
tokens=nltk.word_tokenize(raw)
porter=nltk.PorterStemmer() #提取器1
lancaster=nltk.LancasterStemmer() #提取器2 just so so
[porter.stem(t) for t in tokens]
[lancaster.stem(t) for t in tokens
13.將結果寫進文件。output_file=open('output.txt','w')
words=set(nltk.corpus.genesis.words('english-kjv.txt')
for word in sorted(words):
output_file.write(word+"\n")
from textwrap import fill
format='%s(%d)'
pieces=[format % (word,len(word) ) for word in saying]
output=' . join(pieces)
wrapped=fill(output)
print wrapped
總結
以上是生活随笔為你收集整理的python自然语言处理第三章:处理原始文本的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: execl表格同时打开多个独立窗口编辑
- 下一篇: websocket python爬虫_p