0、hanlp简介
HanLP是一系列模型与算法组成的NLP工具包,由大快搜索主导并完全开源,目标是普及自然语言处理在生产环境中的应用。HanLP具备功能完善、性能高效、架构清晰、语料时新、可自定义的特点。
开源网址:HanLP: Han Language Processing
但由于hanlp是用java来实现的,要在python中使用hanlp,只能通过调用pyhanlp这个包来。
但是pyhanlp里面有一些功能仍然不支持python直接调用,比如汉字转拼音,这时候就需要从python中启动jvm并指定Hanlp的jar路径来使用其他功能了。
1、下载并配置文件
(1)从开源网址中下载jar、data、hanlp.properties并修改配置文件:
1、下载:data.zip
下载后解压到任意目录,接下来通过配置文件hanlp.properties告诉HanLP数据包的位置。
data
│
├─dictionary
└─model
用户可以自行增删替换,如果不需要句法分析等功能的话,随时可以删除model文件夹。
2、下载jar和配置文件:hanlp-release.zip
配置文件hanlp.properties的作用是告诉HanLP数据包的位置,只需修改第一行为data的父目录即可:
比如data目录是/Users/hankcs/Documents/data,那么root=/Users/hankcs/Documents/ 。
(2)从python中启动jvm以及添加jar包路径
from jpype import startJVM,shutdownJVM
import jpype
jvm_default = jpype.getDefaultJVMPath()
jar_path = "-Djava.class.path=C:/Users/1/Desktop/hanlp-1.70/hanlp-1.7.0.jaxxxxxxdxxr;C:/Users/1/Desktop/hanlp-1.70;"
#启动JVM,需要参数:1、jvm路径; 2、jar_path指向hanlp的jar包路径以及jar包本身路径
startJVM(jvm_default,jar_path)
其中-Djava.class.path是用来添加jar包到classpath中,然后用startJVM来启动jvm。
startJVM第一个参数是系统内的jvm位置,第二个为*arg参数,此处放置classpath。
2、启动汉字转拼音模块
from jpype import JClass
pinyin = JClass('com.hankcs.hanlp.dictionary.py.PinyinDictionary')
pypinyin = pinyin.convertToPinyin("测试")
以上得到的是java的ArrayList类型,需要将他装换为string类型:
res = pypinyin.toString()
print(res)
结果如下:
'[ce4, shi4]'
3、最后记得关闭JVM
shutdownJVM()