安装了hanlp,用python运行代码时,出错。
from jpype import *
startJVM(getDefaultJVMPath(), "-Djava.class.path=C:\\Users\\hsq\\Downloads\\Hanlp-hanlp.1.8.4.jar;C:\\Users\\hsq\\Downloads\\Hanlp",
"-Xms1g",
"-Xmx1g") # 启动JVM,Linux需替换分号;为冒号:
print("=" * 30 + "HanLP分词" + "=" * 30)
HanLP = JClass('com.hankcs.hanlp.HanLP')
# 中文分词
print(HanLP.segment('小明硕士毕业于中国科学院计算所,后在日本京都大学深造。'))
print("-" * 70)
shutdownJVM()
显示错误
Traceback (most recent call last):
File "C:\Users\hsq\Desktop\1.py", line 8, in <module>
HanLP = JClass('com.hankcs.hanlp.HanLP')
File "C:\Users\hsq\AppData\Local\Programs\Python\Python310\lib\site-packages\jpype\_jclass.py", line 99, in __new__
return _jpype._getClass(jc)
TypeError: Class com.hankcs.hanlp.HanLP is not found
这是为什么出错?
问题可能出在环境配置上。建议先确认你的Java环境是否已经正确安装并配置好了环境变量。另外,你可以尝试使用jpype.startJVM()的另一个参数-Djava.class.path指定hanlp的路径,例如:
startJVM(getDefaultJVMPath(), "-Djava.class.path=/path/to/hanlp.jar:/path/to/hanlp-1.x.x/", "-Xms1g", "-Xmx1g")
其中/path/to/hanlp.jar和/path/to/hanlp-1.x.x/分别为hanlp的jar包和所在的目录路径。另外,在Windows平台下,路径中的\需要替换为/。
Github地址:https://github.com/hankcs/HanLP
安装:pip install pyhanlp -i https://pypi.douban.com/simple/
修改自定义词典方法:修改~\Anaconda3\Lib\site-packages\pyhanlp\static\data\dictionary\custom\ CustomDictionary.txt
路径下的文件
from pyhanlp import *
def keyword_hanlp(content):
"""基于textrank算法"""
keywords = HanLP.extractKeyword(content, 50)
return keywords