数学之路(3)-机器学习(3)-机器学习算法-贝叶斯定理(2)

我们运用朴素贝叶斯技术对文本完成分类,我们编写网络爬虫代码  在相关新闻网中下面搜索几类新闻,提取词条,形成词条概率数据,新闻类别及爬虫所爬取链接如下:

汽车 http://finance.chinanews.com/auto/gd.shtml
财经 http://finance.chinanews.com/cj/gd.shtml
健康 http://www.chinanews.com/jiankang.shtml
教育 http://www.chinanews.com/jiaoyu.shtml
军事 http://www.chinanews.com/mil/news.shtml


我们下载网页解析库Beautiful Soup

Beautiful Soup的最新版本

可以在此获取

http://www.crummy.com/software/BeautifulSoup/bs4/download/

 

文档:

http://www.crummy.com/software/BeautifulSoup/bs4/doc/


首先,我们生成一个目录文件,内容如下:

汽车 http://finance.chinanews.com/auto/gd.shtml
财经 http://finance.chinanews.com/cj/gd.shtml
IT http://finance.chinanews.com/it/gd.shtml
体育 http://www.chinanews.com/sports.shtml
军事 http://www.chinanews.com/mil/news.shtml


然后对目录文件读取生成样本类别数据

#!/usr/bin/env python
#-*- coding: utf-8 -*-
#code:myhaspl@qq.com
#http://blog.csdn.net/myhaspl
#bayes文本分类
#本程序仅做机器学习研究
#本程序对新闻爬取的工作原理与搜索引擎相同,通过分析链接
#直接搜索新闻,计算词条概率

import numpy as np
import jieba
import urllib2
from bs4 import BeautifulSoup
import re

#读取网上新闻搜索目录
txt_class=[]
myclassfl = open('ClassList.txt')
try:
myclass_str = myclassfl.read()
myclass_str=unicode(myclass_str,'utf-8')
myclass_text=myclass_str.split()
for ii in xrange(0,len(myclass_text),2):
print ".",
txt_class.append((myclass_text[ii],myclass_text[ii+1]))
finally:
myclassfl.close()



接着将网页链接进行提取,比如下面是对军事网页的搜索

#爬取军事网页
#提取链接
links=[]
pattern = re.compile(r'(.*?)/\d+\.shtml')
purl='http://www.chinanews.com/mil/news.shtml'
page=urllib2.urlopen(purl)
soup = BeautifulSoup(page,fromEncoding="gb18030")
for link in soup.find_all('a'): 
    mylink=link.get('href')
    match = pattern.match(mylink)
    if match:
        links.append(mylink)


接着提取新闻链接的正文内容

#提取正文内容
ybtxt=[]
print u"\n提取正文内容"
for mypage in links:
    my_page=urllib2.urlopen(mypage)
    my_soup = BeautifulSoup(my_page,fromEncoding="gbk")
    print ".",
 ...............
    zw_start=my_txt.find(my_fs)+8
    last_txt=my_txt[zw_start:len(my_txt)]
    zw_end=last_txt.find(my_fs)
    page_content=my_txt[zw_start:zw_start+zw_end]
.............................



本博客所有内容是原创,如果转载请注明来源

http://blog.csdn.net/myhaspl/




  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值