Python中文分词工具之结巴分词用法实例总结【经典案例】
作者:捂汗县长 时间:2023-05-05 01:46:30
本文实例讲述了Python中文分词工具之结巴分词用法。分享给大家供大家参考,具体如下:
结巴分词工具的安装及基本用法,前面的文章《Python结巴中文分词工具使用过程中遇到的问题及解决方法》中已经有所描述。这里要说的内容与实际应用更贴近——从文本中读取中文信息,利用结巴分词工具进行分词及词性标注。
示例代码如下:
#coding=utf-8
import jieba
import jieba.posseg as pseg
import time
t1=time.time()
f=open("t_with_splitter.txt","r") #读取文本
string=f.read().decode("utf-8")
words = pseg.cut(string) #进行分词
result="" #记录最终结果的变量
for w in words:
result+= str(w.word)+"/"+str(w.flag) #加词性标注
f=open("t_with_POS_tag.txt","w") #将结果保存到另一个文档中
f.write(result)
f.close()
t2=time.time()
print("分词及词性标注完成,耗时:"+str(t2-t1)+"秒。") #反馈结果
其中t_with_splitter.txt文件内容如下:
脚本之家是国内专业的网站建设资源、脚本编程学习类网站,提供asp、php、asp.net、javascript、jquery、vbscript、dos批处理、网页制作、网络编程、网站建设等编程资料。
Python2.7.9平台运行后出现如下图所示的错误提示:
查阅相关资料后发现,需要在开头加上:
import sys
reload(sys)
sys.setdefaultencoding( "utf-8" )
最终代码应为:
#coding=utf-8
import jieba
import jieba.posseg as pseg
import time
import sys
reload(sys)
sys.setdefaultencoding( "utf-8" )
t1=time.time()
f=open("t_with_splitter.txt","r") #读取文本
string=f.read().decode("utf-8")
words = pseg.cut(string) #进行分词
result="" #记录最终结果的变量
for w in words:
result+= str(w.word)+"/"+str(w.flag) #加词性标注
f=open("t_with_POS_tag.txt","w") #将结果保存到另一个文档中
f.write(result)
f.close()
t2=time.time()
print("分词及词性标注完成,耗时:"+str(t2-t1)+"秒。") #反馈结果
运行成功:
Editplus打开t_with_POS_tag.txt文件如下图所示:
希望本文所述对大家Python程序设计有所帮助。
标签:Python,中文分词,结巴分词
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
如何通过shell脚本自动生成vue文件详解
2024-05-22 10:28:35
![](https://img.aspxhome.com/file/2023/1/123701_0s.jpg)
Vue中使用webpack别名的方法实例详解
2024-05-11 09:13:41
Python数字比较与类结构
2023-07-29 13:33:51
![](https://img.aspxhome.com/file/2023/3/125053_0s.png)
python elasticsearch环境搭建详解
2021-03-31 03:50:42
微信小程序实现录音
2024-04-22 13:25:41
![](https://img.aspxhome.com/file/2023/4/135694_0s.jpg)
Perl使用chdir的实例代码
2023-02-13 19:33:56
深入理解JavaScript系列(38):设计模式之职责链模式详解
2024-06-05 09:54:55
Windows 8.1 64bit下搭建 Scrapy 0.22 环境
2023-07-23 12:51:08
![](https://img.aspxhome.com/file/2023/7/64327_0s.png)
2009年情人节网站logo欣赏
2009-02-15 12:13:00
![](https://img.aspxhome.com/file/UploadPic/20092/15/valentines09-google-50s.gif)
SQL语句解析执行的过程及原理
2024-01-26 21:11:55
![](https://img.aspxhome.com/file/2023/1/127571_0s.png)
Python简易版图书管理系统
2022-06-07 21:11:10
Python retrying 重试机制的使用方法
2023-09-21 22:52:36
![](https://img.aspxhome.com/file/2023/0/103770_0s.png)
Python利用Turtle绘制Technoblade的示例代码
2023-08-23 22:43:01
![](https://img.aspxhome.com/file/2023/0/62260_0s.png)
关于利用:first-letter实现首字下沉的一些看法
2010-04-20 17:19:00
![](https://img.aspxhome.com/file/UploadPic/20104/20/first-letter_no_float-38s.png)
Pytorch中Softmax和LogSoftmax的使用详解
2022-09-24 07:36:19
如何增强网站数据库Access文件的安全性
2008-11-13 16:58:00
JavaScript输入邮箱自动提示实例代码
2024-02-27 03:01:43
浅谈终端直接执行py文件,不需要python命令
2022-12-25 14:38:11
浅谈vue项目利用Hbuilder打包成APP流程,以及遇到的坑
2024-04-10 13:46:11
![](https://img.aspxhome.com/file/2023/3/139693_0s.jpg)
Javascript中的函数声明与函数表达式(奇技淫巧)
2024-04-23 09:08:43