#一般需要导入该库。导入方法,打开cmd命令窗口或者anaconda prompt:
#pip install -i https://pypi.tuna.tsinghua.edu.cn/simple jieba(最后一个参数是包名)
#如果想安装对应版本的包,只需在包名后面加“==版本号”即可
import jieba
#分词
def cut_word(Test):
# jieba 默认启用了HMM(隐马尔科夫模型)进行中文分词
seg_list = jieba.cut(Test,cut_all=True) # 分词
#返回一个以分隔符'/'连接各个元素后生成的字符串
line = "/".join(seg_list)
word = out_stopword(line)
#print(line)
#列出关键字
print("\n关键字:\n"+word)
#去除停用词
def out_stopword(seg):
#打开写入关键词的文件
keyword = open('D:\keyword.txt', 'w+', encoding='utf-8')
print("去停用词:\n")
wordlist = []
#获取停用词表
#开源网站GitHub上有整理好的停用词表,可以下载使用
#goto456/stopwords: 中文常用停用词表(哈工大停用词表、百度停用词表等)——https://github.com/goto456/stopwords
#停用词文本C:\Users\Administrator\hit_stopwords.txt
stop = open('D:\hit_stopwords.txt', 'r+', encoding='utf-8')
#用‘\n’去分隔读取,返回一个一维数组
stopword = stop.read().split("\n")
#遍历分词表
for key in seg.split('/'):
#print(key)
#去除停用词,去除单字,去除重复词
if not(key.strip() in stopword) and (len(key.strip()) > 1) and not(key.strip() in wordlist) :
wordlist.append(key)
print(key)
keyword.write(key+"\n")
#停用词去除END
stop.close()
keyword.close()
return '/'.join(wordlist)
if __name__ == '__main__':
#打开txt文本
Rawdata = open('D:\Rowdatas.txt','r+',encoding='utf-8')
#将文本读取并存储到text中
text = Rawdata.read()
#调用分词,将待分词的文本作为参数传入方法中
cut_word(text)
#关闭文本
Rawdata.close()
jieba中文分词的实现(含去除停用词,注释详尽,欢迎批评指导)
最新推荐文章于 2024-06-27 01:11:28 发布