中文分词 jieba和HanLP

安装python包:

pip install nltk
pip install jieba
pip install pyhanlp
pip install gensim

使用jieba进行分词

import jieba
content = "现如今,机器学习和深度学习带动人工智能飞速的发展,并在图片处理、语音识别领域取得巨大成功。"
# cut_all 参数用来控制是否采用全模式
segs_1 = jieba.cut(content, cut_all=False)
print("/".join(segs_1))
segs_3 = jieba.cut(content, cut_all=True)
print("/".join(segs_3))
segs_4 = jieba.cut_for_search(content)  # 默认不使用 HMM 模型
print("/".join(segs_4))
segs_5 = jieba.lcut(content)
print(segs_5)
# 获取词性
import jieba.posseg as psg
print([(x.word,x.flag) for x in psg.lcut(content)])
# 获取分词结果中词列表的 top n
from collections import Counter
top5= Counter(segs_5).most_common(5)
print(top5)
txt = "铁甲网是中国最大的工程机械交易平台。"
print(jieba.lcut(txt))
jieba.add_word("铁甲网")
# jieba.load_userdict('user_dict.txt')
print(jieba.lcut(txt))

结果为:
[‘铁甲网’, ‘是’, ‘中国’, ‘最大’, ‘的’, ‘工程机械’, ‘交易平台’, ‘。’]

使用pyhanlp进行分词

from pyhanlp import *
content = "现如今,机器学习和深度学习带动人工智能飞速的发展,并在图片处理、语音识别领域取得巨大成功。"
print(HanLP.segment(content))
txt = "铁甲网是中国最大的工程机械交易平台。"
print(HanLP.segment(txt))
CustomDictionary.add("铁甲网")
CustomDictionary.insert("工程机械", "nz 1024")
CustomDictionary.add("交易平台", "nz 1024 n 1")
print(HanLP.segment(txt))

结果为:
[铁甲网/nz, 是/vshi, 中国/ns, 最大/gm, 的/ude1, 工程机械/nz, 交易平台/nz, 。/w]

猜你喜欢

转载自blog.csdn.net/lhxsir/article/details/83303414