最近在研究中文分词及自然语言相关的内容,关注到JAVA环境下的HanLP,HanLP是一个致力于向生产环境普及NLP技术的开源Java工具包,支持中文分词(N-最短路分词、CRF分词、索引分词、用户自定义词典、词性标注),命名实体识别(中国人名、音译人名、日本人名、地名、实体机构名识别),关键词提取,自动摘要,短语提取,拼音转换,简繁转换,文本推荐,依存句法分析(MaxEnt依存句法分析、神经网络依存句法分析)。
由于自己才疏学浅,对JAVA方面了解不多,所以打算在Python环%2, line 5, in <module>
startJVM(getDefaultJVMPath())
File “C:\Python27\lib\site-packages\jpype\_core.py”, line 44, in startJVM
_jpype.startup(jvm, tuple(args), True)
RuntimeError: First paramter must be a string or unicode at src/native/python/jpype_module.cpp:31
很有可能是没有配置JDK的环境变量或安装的JDK的位数与Python的位数不一致。导致 getDefaultJVMPath() 方法返回的是 None。
下载HanLP
- 你可以直接下载Portable版的jar,零配置。
- 也可以使用自定义的HanLP——HanLP由3部分组成:类库hanlp.jar包、模型data包、配置文件hanlp.properties,请前往项目主页下载最新版:https://github.com/hankcs/HanLP/releases。对于非portable版,下载后,你需要编辑配置文件第一行的root指向data的父目录。
这里,假设新建了一个目录(假定为C:\hanlp),把hanlp.jar和hanlp.properties(portable版的话,仅需一个hanlp-portable.jar)放进去。
Python调用
以下是我的测试:(使用的是Python,与Python3 相比多了 .toString() 这一操作)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
#!/usr/bin/env python # -*- coding: utf-8 -*- from jpype import * startJVM(getDefaultJVMPath(), "-Djava.class.path=G:\TextAnalysis\libs\hanlp-portable-1.3.1.jar;G:\TextAnalysis\libs") HanLP = JClass('com.hankcs.hanlp.HanLP') my_words = u'HanLP是一个致力于向生产环境普及NLP技术的开源Java工具包' # 标准分词 print(HanLP.segment(my_words).toString()) #索引分词 IndexTokenizer = JClass('com.hankcs.hanlp.tokenizer.IndexTokenizer') print(IndexTokenizer.segment(my_words).toString()) # 关键词提取 document = u"JPype是一个能够让 Python 代码方便地调用 Java 代码的工具," \ u"JPype并没有像IKVM(一款可以在.NET环境中运行JAVA代码的工具)那样实现自己的JVM," \ u"而是以pipe方式调用原生JVM。如果要使用JPype就需要先安装JDK。" print(HanLP.extractKeyword(document, 3).toString()) # 自动摘要 print(HanLP.extractSummary(document, 2).toString()) shutdownJVM() |
参考文章:
打赏作者

File “C:/Users/Administrator/PycharmProjects/untitled5/unn.py”, line 8, in
HanLP = JClass(‘com.hankcs.hanlp.HanLP’)
File “C:\Python34\lib\site-packages\jpype\_jclass.py”, line 55, in JClass
raise _RUNTIMEEXCEPTION.PYEXC(“Class %s not found” % name)
若报错是这样的话 是有什么问题呢 请问
类没有找到,是否正确加载jar包?
jpype._jexception.ExceptionPyRaisable: java.lang.Exception: Class com.hankcs.hanlp.HanLP not found,类找不到,请问你是怎么放置com下面的文件夹的?先谢谢啦
直接放在项目文件夹下