《python进行自然语言处理》练习处理HTML内容的时候出现ImportError: No module named BeautifulSoup错误

本文解决了Python自然语言处理中使用nltk清理HTML标记的问题,并介绍了如何正确使用BeautifulSoup4来替代nltk自带的HTML清理功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在练习Python自然语言处理的时候,遇到了下面的错误:

# -*- coding: utf-8 -*-
"""
Created on Wed Dec 30 17:10:30 2015
@author: mahao
"""
#错误的形式
import nltk  
from urllib.request import urlopen  
from bs4 import BeautifulSoup
url = "http://news.bbc.co.uk/2/hi/health/2284783.stm"  
html = urlopen(url).read()  
#print(html[:60]) 
raw = nltk.clean_html(html)
#print(nltk.word_tokenize(raw))
tokens = nltk.word_tokenize(raw)  
tokens=tokens[96:399]  
text=nltk.Text(tokens)
print(text.concordance('gene'))
"""
<span style="color:#ff0000;"><span style="color:#ff0000;">报错:ImportError: No module named 'BeautifulSoup</span>'</span>
"""
最后参考了 Beautiful Soup 4.2.0 文档,看到了:

原来Beautifusoup4改名为bs4了,所以把:

改为:


但是,改完之后,运行又会出现:

NotImplementedError: To remove HTML markup, use BeautifulSoup's get_text() function

原来是使用clean_html()函数出错,网站:http://stackoverflow.com/questions/10524387/beautifulsoup-get-text-does-not-strip-all-tags-and-javascript介绍:  
以后的版本,似乎不支持clean_html()和clean_url()这两个函数  
Support for clean_html and clean_url will be dropped for future versions of nltk. Please use BeautifulSoup for now...it's very unfortunate.  

然后我查了一下Beautiful Soup 4.2.0 文档,才发现,BeautifulSoup使用已经发生了改变,使用方式参照上面的例子,然后最终程序:

import nltk  
from urllib.request import urlopen  
from bs4 import BeautifulSoup
url = "http://news.bbc.co.uk/2/hi/health/2284783.stm"  
html = urlopen(url).read()  
#print(html[:60]) 
soup = BeautifulSoup(html)
raw = soup.get_text()
#print(nltk.word_tokenize(raw))
tokens = nltk.word_tokenize(raw)  
tokens=tokens[96:399]  
text=nltk.Text(tokens)
print(text.concordance('gene'))

然后就ok了!!!

python3令人头疼但快乐着。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值