1. 程式人生 > >python3.x如何從網際網路獲取想要的文章,及轉化為nltk可以處理的文字

python3.x如何從網際網路獲取想要的文章,及轉化為nltk可以處理的文字

from urllib.request import urlopen
from bs4 import BeautifulSoup
from nltk import word_tokenize
import nltk
#2種方式解析HTML中的文字
url = "http://news.bbc.co.uk/2/hi/health/2284783.stm"
html = urlopen(url).read().decode('utf8')
print(html[:60])
#print(html)
#第一種,使用find和rfind查詢到文字的開始位置和結束位置,使用python的切片功能
raw = BeautifulSoup(html,'lxml').get_text()#如果出現bs4.FeatureNotFound:(沒有安裝解析器只需在cmd下:pip install lxml即可)


tokens = word_tokenize(raw)
print(tokens[:10])#檢測HTML文字
print(raw.find("Blondes 'to die out in 200 years'"))
print(raw.rfind("The frequency of blondes may drop but they won't disappear."))
#print(raw[22:2449])列印整篇報道


#第二種,使用beautifulsoup自帶的功能,匹配到相應的模組,輸出文字內容(此時不包含標題,如果需要還需再找相應的模組)
bs = BeautifulSoup(html,'lxml')
print(bs.find("div",class_='bodytext').get_text())
#過濾無關內容
tokens = tokens[110:390]
text = nltk.Text(tokens)#把文字轉化為nltk文字進行後續處理
print(text.concordance('gene'))