python实现的读取网页并分词功能示例

yipeiwu_com5年前Python基础

本文实例讲述了python实现的读取网页并分词功能。分享给大家供大家参考,具体如下:

这里使用分词使用最流行的分词包jieba,参考:https://github.com/fxsjy/jieba

或点击此处本站下载jieba库

代码:

import requests
from bs4 import BeautifulSoup
import jieba
# 获取html
url = "http://finance.ifeng.com/a/20180328/16049779_0.shtml"
res = requests.get(url)
res.encoding = 'utf-8'
content = res.text
# 添加至bs4
soup = BeautifulSoup(content, 'html.parser')
div = soup.find(id = 'main_content')
# 写入文件
filename = 'news.txt'
with open(filename,'w',encoding='utf-8') as file_object:
  # <p>标签的处理
  for line in div.findChildren():
    file_object.write(line.get_text()+'\n')
# 使用分词工具
seg_list = jieba.cut("我来到北京清华大学", cut_all=True)
print("Full Mode: " + "/ ".join(seg_list)) # 全模式
seg_list = jieba.cut("我来到北京清华大学", cut_all=False)
print("Default Mode: " + "/ ".join(seg_list)) # 精确模式
seg_list = jieba.cut("他来到了网易杭研大厦") # 默认是精确模式
print(", ".join(seg_list))
with open(filename,'r',encoding='utf-8') as file_object:
  with open('cut_news.txt','w',encoding='utf-8') as file_cut_object:
    for line in file_object.readlines():
      seg_list = jieba.cut(line,cut_all=False)
      file_cut_object.write('/'.join(seg_list))

爬取结果:

分词结果:

更多关于Python相关内容感兴趣的读者可查看本站专题:《Python数学运算技巧总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总

希望本文所述对大家Python程序设计有所帮助。

相关文章

Python 判断文件或目录是否存在的实例代码

使用 os 模块 判断文件是否存在 os.path.isfile(path) 判断目录是否存在 os.path.isdir(path) 判断路径是否存在 # 使用 path 模块 o...

python3.0 字典key排序

IDLE 3.0 >>> dic = {"aa":1,"bb":2,"ab":3} >>> dic {'aa': 1, 'ab': 3, 'bb':...

PyQt打开保存对话框的方法和使用详解

PyQt之打开保存对话框(QFileDialog)的方法和使用 一、控件说明 QFileDialog是用于打开和保存文件的标准对话框,继承自QDialog类。 QFileDialog在打...

用python打印菱形的实操方法和代码

python怎么打印菱形?下面给大家带来三种方法: 第一种 rows = int(input('请输入菱形边长:\n')) row = 1 while row <= row...

在Linux中通过Python脚本访问mdb数据库的方法

在 linux 系统中连接 mdb 数据库,直接连接的话,mdb 默认的驱动无法识别非 windows 的路径, 所以不能使用常规的连接方式 DRIVER={Microsoft Ac...