栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

《金融非结构化数据预处理》实验项目

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

《金融非结构化数据预处理》实验项目

实验题目

使用python语言和数据库,完成以下内容
实验内容1:文本数据分词
针对材料中的新闻数据,使用结巴分词插件,完成分词程序的编写,对提供的文本进行分词标注。
实验2:去除停用词
使用停用词典,去除分词后文本中的停用词。

实验代码 1. 引入库
import jieba
import xlrd
import re
import xlwt
from xlutils.copy import copy
2. 打开文件
data = xlrd.open_workbook('新闻数据.xls')
sheet = data.sheet_by_index(0)
3. 创建停用词列表

直接打开有错误,因文件是ANSI编码,需要使用encoding='ANSI’打开

stopwords = [line.strip() for line in open('中文停用词表.txt',encoding='ANSI').readlines()]
4. 编写函数,检查字符串是否含有中文
def haveChinese(string):
    for ch in string:
        if u'u4e00' <= ch <= u'u9fff':
            return True
5. 分词,去除停用词

去除停用词后,仍需要去除的有空格、纯数字、纯英文、一些乱码字符等,一开始尝试逐个去除空格、纯数字、纯英文,并把乱码字符添加到停用词表中,后来意识到直接去除不含有中文字符的词语就可以直接解决以上问题。

# 分别获取需要分词的两列数据
title = sheet.col_values(3); # 获取第四列内容(标题数据)
content = sheet.col_values(4); # 获取第五列内容(评论正文数据)
new_data = copy(data)  # 将xlrd对象拷贝转化为xlwt对象
new_sheet = new_data.get_sheet(0)  # 获取转化后工作簿中的第一个表格
for i in range(1,60001):
    seg_title = jieba.lcut(title[i])    # 精简模式,返回一个列表类型的结果
    seg_content = jieba.lcut(content[i])
    # 输出结果为outstr
    outstr = ''                   
    # 标题去停用词
    for word in seg_title:
        # 去除停用词表中内容
        if word not in stopwords:
            # 去除不包含中文的词
            if haveChinese(word):
                outstr += word
                outstr += "/"
    # 评论去停用词
    for word in seg_content:
        if word not in stopwords:
            # 去除不包含中文的词
            if haveChinese(word):
                outstr += word
                outstr += "/"
    new_sheet.write(i, 6, outstr)
    print(outstr)
    print("————————————已写入数据————————————")
    
new_data.save("segContent.xls")  # 保存工作簿
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/979949.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号