NLP入门 1.0 nltk 小试牛刀

    from urllib import request
    url = 'https://python.org/'
    html=request.urlopen(url)
    html=html.read()
    html
#导入url网址里面的HTML内容

NLP入门 1.0 nltk 小试牛刀_第1张图片
可以看出很多杂乱的HTML代码和网页内容混合在一起,需要我们进行清洗。

import nltk
from bs4 import BeautifulSoup
import re
soup = BeautifulSoup(html,'lxml')
clean=soup.get_text()
tokens = [tok for tok in clean.split() ]
print(tokens[0:100])

直接用nltk这个现在不行了,要借助bs4来进行处理。
NLP入门 1.0 nltk 小试牛刀_第2张图片比之前好多了,进行词频统计。

Freq_dist_nltk = nltk.FreqDist(tokens)
print(Freq_dist_nltk)
for k,v in Freq_dist_nltk.items():
    print(str(k)+':'+str(v))

NLP入门 1.0 nltk 小试牛刀_第3张图片
可以看出很多无用的标点符号和词语,我们用停用词表进行去除。

    import nltk
    nltk.download('stopwords')
    import nltk
    nltk.download('punkt')
    import matplotlib
    from nltk.corpus import stopwords
    stopwords=stopwords.words('english')
   clean_tokens= [tok for tok in tokens if len(tok.lower())>1 and (tok.lower()not in stopwords)  ]
   Freq_dist_nltk = nltk.FreqDist(clean_tokens)
   freplot = Freq_dist_nltk.plot(20,cumulative = False)

NLP入门 1.0 nltk 小试牛刀_第4张图片
经过去停用词后结果还是令人满意的,好了,简单的尝试一下用nltk,还是不错的。

你可能感兴趣的:(NLP)