具体代码如下
# -*- encoding=utf-8 -*-
import jieba.analyse
import jieba
import pandas as pd
# 载入自定义词典
jieba.load_userdict('dict.txt')
# 载入自定义停止词
jieba.analyse.set_stop_words('stop_words.txt')
# 去掉中英文状态下的逗号、句号
def clearSen(comment):
comment = comment.strip()
comment = comment.replace('、', '')
comment = comment.replace(',', '。')
comment = comment.replace('《', '。')
comment = comment.replace('》', '。')
comment = comment.replace('~', '')
comment = comment.replace('…', '')
comment = comment.replace('\r', '')
comment = comment.replace('\t', ' ')
comment = comment.replace('\f', ' ')
comment = comment.replace('/', '')
comment = comment.replace('、', ' ')
comment = comment.replace('/', '')
comment = comment.replace('。', '')
comment = comment.replace('(', '')
comment = comment.replace(')', '')
comment = comment.replace('_', '')
comment = comment.replace('?', ' ')
comment = comment.replace('?', ' ')
comment = comment.replace('了', '')
comment = comment.replace('➕', '')
comment = comment.replace(':', '')
return comment
# 读取数据
# zhengce_content = pd.read_table('0020.txt', sep=',') # 后面有sep的讲解
zhengce_content = pd.read_table('./2016_wenben/0007.txt', sep='\t')
# 数据重命名
zhengce_content.columns = ['content']
# 文件写入
outputfile = open('2016_jieba_output.txt', 'a+', encoding="utf-8")
# 这个是分词后你要写入哪个文件,就填入哪个文件的地址,文件地址的写法,可以看我的文章
for each in zhengce_content['content']:
# 清除标点符号,使用了上面的函数
kk = clearSen(each)
# 精确模式切词
seg_list = jieba.cut(kk)
comment = " ".join(seg_list)
print(comment)
# 写出数据
outputfile.write(comment)
# 关闭文件
outputfile.close()
在此之前,你需要弄懂几个问题
1.结巴库,pandas库的下载安装
2.自定词典,停用词,需要处理的文件,处理后写入的文件,都需要是txt文件且为utf-8格式
3.文件的路径指定,可以参考我的这个文章https://blog.csdn.net/weixin_44301621/article/details/89513870
接下来是sep的讲解
输入以下代码时
print('123', 'abc','zhangsan')
# 输出结果 123 abc zhangsan
当输入以下代码时
print('123', 'abc','zhangsan',sep=',')
# 输出结果 123,abc,zhangsan
也就是说,sep是在指定分隔符,我们要以什么符号为分隔符。在最上面jieba分词中代码,sep指定的是,读取文件时,以什么符号为分割,来读取文件。
;