本文目录导读:

我来详细介绍如何使用HanLP处理中文的Python案例。
安装HanLP
首先安装HanLP,推荐使用2.x版本:
pip install hanlp
如果需要完整功能,可以安装完整版:
pip install hanlp[full]
基本使用案例
示例1:基础分词和词性标注
import hanlp
# 加载预训练模型(首次运行会自动下载)
tokenizer = hanlp.load(hanlp.pretrained.tok.COARSE_ELECTRA_SMALL_ZH)
pos = hanlp.load(hanlp.pretrained.pos.CTB9_POS_ELECTRA_SMALL)
ner = hanlp.load(hanlp.pretrained.ner.MSRA_NER_ELECTRA_SMALL_ZH)
# 测试文本
text = "我爱自然语言处理技术,它让计算机能够理解人类语言。"
# 分词
words = tokenizer(text)
print("分词结果:", words)
# 词性标注
pos_tags = pos(words)
print("词性标注:", list(zip(words, pos_tags)))
# 命名实体识别
entities = ner(words)
print("命名实体:", entities)
示例2:依存句法分析
import hanlp
# 加载依存句法分析模型
dep = hanlp.load(hanlp.pretrained.dep.CTB9_DEP_ELECTRA_SMALL)
# 执行依存句法分析
sentences = ["人工智能正在改变世界", "我喜欢学习Python编程"]
for sent in sentences:
result = dep(sent)
print(f"句子:{sent}")
print("依存句法分析结果:")
for i, item in enumerate(result):
print(f" {i}: {item}")
print()
示例3:文本分类
from hanlp.components.classification.transformer_classifier import TransformerClassifier
# 加载文本分类模型
classifier = TransformerClassifier()
classifier.load("https://hanlp.hankcs.com/model/classification/chn_sentiment_clf_electra_small.zip")
# 情感分析示例
texts = [
"这个产品真的很好用,我非常喜欢!",
"质量太差了,完全不满意。",
"一般般吧,没什么特别的感觉。"
]
for text in texts:
result = classifier(text)
print(f"文本:{text}")
print(f"分类结果:{result}")
print()
示例4:语义角色标注
import hanlp
# 加载语义角色标注模型
srl = hanlp.load(hanlp.pretrained.srl.CHNSRL_ELECTRA_SMALL)
# 示例句子
sentences = [
"李明昨天在北京买了两本书",
"公司决定暂停新产品研发"
]
for sent in sentences:
result = srl(sent)
print(f"句子:{sent}")
print("语义角色标注结果:")
for pred, args in result:
print(f" 谓词:{pred}")
for arg_type, arg_text in args:
print(f" {arg_type}: {arg_text}")
print()
示例5:综合NLP处理
import hanlp
from hanlp.components.pipeline import Pipeline
# 创建处理管道
tok = hanlp.load(hanlp.pretrained.tok.COARSE_ELECTRA_SMALL_ZH)
pos = hanlp.load(hanlp.pretrained.pos.CTB9_POS_ELECTRA_SMALL)
ner = hanlp.load(hanlp.pretrained.ner.MSRA_NER_ELECTRA_SMALL_ZH)
dep = hanlp.load(hanlp.pretrained.dep.CTB9_DEP_ELECTRA_SMALL)
# 组合成管道
pipeline = Pipeline([
('tok', tok),
('pos', pos),
('ner', ner),
('dep', dep)
])
# 处理文本
text = "华为在深圳建立了新的研发中心,主要研究人工智能技术。"
result = pipeline(text)
print("综合处理结果:")
print(result)
示例6:批量处理
import hanlp
import time
# 加载模型
tokenizer = hanlp.load(hanlp.pretrained.tok.COARSE_ELECTRA_SMALL_ZH)
# 批量处理文本
texts = [
"自然语言处理是人工智能的重要分支",
"深度学习在NLP领域取得了巨大成功",
"BERT模型改变了NLP的研究范式",
"大语言模型如GPT展现出了惊人的能力"
]
# 批量分词
start_time = time.time()
results = tokenizer(texts)
end_time = time.time()
print("批量处理结果:")
for i, (text, words) in enumerate(zip(texts, results)):
print(f"文本{i+1}: {text}")
print(f"分词: {words}")
print()
print(f"处理耗时:{end_time - start_time:.2f}秒")
高级应用示例
示例7:自定义词典
import hanlp
# 加载分词器
tokenizer = hanlp.load(hanlp.pretrained.tok.COARSE_ELECTRA_SMALL_ZH)
# 自定义词典(可以在加载模型时指定)
custom_dict = {
"自然语言处理": ["自然", "语言", "处理"],
"人工智能": ["人工", "智能"],
"机器学习": ["机器", "学习"]
}
# 使用自定义词典分词
text = "自然语言处理是人工智能的子领域,机器学习是其核心技术"
result = tokenizer(text)
print("默认分词结果:", result)
# 注意:实际使用中可以通过修改模型配置来添加自定义词典
示例8:模型保存和加载
import hanlp
import os
# 加载模型
tokenizer = hanlp.load(hanlp.pretrained.tok.COARSE_ELECTRA_SMALL_ZH)
# 保存模型到本地
save_path = "./my_hanlp_model"
os.makedirs(save_path, exist_ok=True)
tokenizer.save(save_path)
print(f"模型已保存到:{save_path}")
# 从本地加载模型
loaded_tokenizer = hanlp.load(save_path)
# 验证模型正常工作
text = "加载保存的模型测试"
result = loaded_tokenizer(text)
print(f"分词结果:{result}")
性能优化示例
import hanlp
import time
# 使用GPU(如果可用)
hanlp.pretrained.ALL = hanlp.pretrained.ALL.to_device('cuda:0') # 使用GPU
# 或者使用CPU
# hanlp.pretrained.ALL = hanlp.pretrained.ALL.to_device('cpu')
# 加载模型并设置批处理大小
tokenizer = hanlp.load(hanlp.pretrained.tok.COARSE_ELECTRA_SMALL_ZH)
# 批量处理大量文本
texts = ["这是第{}个测试文本,用于性能测试。".format(i) for i in range(100)]
# 设置批处理大小
tokenizer.batch_size = 32
# 执行处理
start_time = time.time()
results = tokenizer(texts)
end_time = time.time()
print(f"处理100个文本耗时:{end_time - start_time:.2f}秒")
print(f"平均每个文本处理时间:{(end_time - start_time)/100*1000:.2f}毫秒")
注意事项
- 模型下载:首次使用时会自动下载模型,需要稳定的网络连接
- 内存使用:大型模型可能占用较多内存,建议根据实际需求选择合适的模型
- GPU加速:如果使用GPU,可以显著提升处理速度
- 模型缓存:下载的模型会缓存在本地,避免重复下载
这些案例涵盖了HanLP的主要功能,你可以根据实际需求选择合适的模型和处理方式。