使用python语言和数据库,完成以下内容
实验内容1:文本数据分词
针对材料中的新闻数据,使用结巴分词插件,完成分词程序的编写,对提供的文本进行分词标注。
实验2:去除停用词
使用停用词典,去除分词后文本中的停用词。
import jieba import xlrd import re import xlwt from xlutils.copy import copy2. 打开文件
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") # 保存工作簿



