python小试中文分词(并解决编码问题)

pip安装thulac

pip install thulac

写一个test.py文件,内容如下:

#coding=utf-8
import thulac   

thu1 = thulac.thulac()  #默认模式
text = thu1.cut("我爱北京天安门", text=True)  #进行一句话分词
print(text)

在cmd中运行该文件:

python test.py

但是发现一个问题,cmd编码为ASCII,中文为GBK,cmd命令行运行出来是乱码,为了在命令行正常显示,将文件内容改为:

#coding=utf-8

import thulac 
thu1 = thulac.thulac()  #默认模式

str="马老师是好同志"
def u2g(str):
    str_utf8=str.decode("UTF-8")
    str_gbk = str_utf8.encode("gbk")
    return str_gbk

print(u2g("马老师是好同志"))
text = thu1.cut("我爱北京天安门", text=True)  #进行一句话分词
print(u2g(text))

参考:

http://thulac.thunlp.org/#%E7%BC%96%E8%AF%91%E5%92%8C%E5%AE%89%E8%A3%85

https://www.cnblogs.com/jxzheng/p/5186490.html

https://www.cnblogs.com/raphael5200/p/5998818.html

猜你喜欢

转载自blog.csdn.net/dongyuguoai/article/details/80963522