开发者社区> 问答> 正文

使用原生 Python 来对文本进行分词

使用原生 Python 来对文本进行分词

展开
收起
珍宝珠 2019-12-03 14:57:10 739 0
1 条回答
写回答
取消 提交回答
  • 首先,我们将抓取一些网页内容。然后来分析网页文本,看看爬下来的网页的主题是关于什么。我们将使用 urllib模块来抓取网页:

    import urllib.request
    response = urllib.request.urlopen('http://php.net/')
    html = response.read()
    print (html)
    
    

    从打印输出中可以看到,结果中包含许多需要清理的HTML标记。我们可以用这个 BeautifulSoup 库来对抓取的文本进行处理:

    from bs4 import BeautifulSoup
    import urllib.request 
    response = urllib.request.urlopen('http://php.net/') 
    html = response.read()
    soup = BeautifulSoup(html,"html5lib")
    text = soup.get_text(strip=True)
    print (text)
    
    

    现在,我们能将抓取的网页转换为干净的文本。这很棒,不是么?

    最后,让我们通过以下方法将文本分词:

    from bs4 import BeautifulSoup 
    import urllib.request 
    response = urllib.request.urlopen('http://php.net/') 
    html = response.read() 
    soup = BeautifulSoup(html,"html5lib") 
    text = soup.get_text(strip=True) 
    tokens = [t for t in text.split()] 
    print (tokens)
    
    2019-12-03 14:57:57
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
From Python Scikit-Learn to Sc 立即下载
Data Pre-Processing in Python: 立即下载
双剑合璧-Python和大数据计算平台的结合 立即下载