Pycharm nltk 实现简单的NLP功能

文章部分内容来自网络 如侵则删

环境搭建

nltk

Pycharm内部下载nltk出了好多错(各种报错),最后下载3.25版本(建议3.25),就可以了。

nltk_data

不建议在线下载,一直报错。
如果你试过网上好多的教程都没不能解决nltk_data带来的各种问题,请联系我。毕竟数据太大了。不方便分享。

几个简单功能

FreqDist(单词数量统计)

stopwords(停顿词,例如:as、the、to)

import nltk
import requests
from bs4 import BeautifulSoup

from nltk.corpus import stopwords

# 设置爬虫的url
url = 'http://php.net/'

# 设置爬虫的header
headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36 SE 2.X MetaSr 1.0"}

# 得到网页内容
response = requests.get(url, headers=headers)

# 设置编码
response.encoding = 'utf8'

# 转换成text内容
html = response.text

soup = BeautifulSoup(html, "html5lib")

# 抓取文本
text = soup.get_text(strip=True)

# 文本分割
tokens = text.split()

# 清洗停顿词之后的数据存放处
clean_tokens = list()

# 停顿词
sr = stopwords.words('english')


for token in tokens:
    # 去除停顿词
    if not token in sr:
        clean_tokens.append(token)

#词频统计
freq = nltk.FreqDist(clean_tokens)

# 输出单词和对应次数
for key, val in freq.items():
    print(str(key) + ':' + str(val))

# 图像展示
freq.plot(10, cumulative=False)

在这里插入图片描述

sent_tokenize(一段话拆成句子)

word_tokenize(一段话拆成单词)

from nltk.tokenize import sent_tokenize
from nltk.tokenize import word_tokenize
mytext = "Hello Adam, how are you? I hope everything is going well" \
         ". Today is a good day, see you dude."

# 一段话 转 句子
print(sent_tokenize(mytext))

# 一段话 转 单词
print(word_tokenize(mytext))

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/Mr_Qian_Ives/article/details/106726110