本文目录导读:

我来详细解释如何在Python中使用jieba自定义词典,包括创建、加载和使用自定义词典的完整案例。
基本概念
自定义词典用于:
- 添加专业术语
- 调整词语权重
- 解决分词不准确的问题
完整案例
1 创建自定义词典文件
首先创建一个文本文件 my_dict.txt:
人工智能 5 n 深度学习 5 n 自然语言处理 5 n 机器学习 3 n 数据分析 3 n 今日头条 5 n jieba分词 3 n 北京理工大学 5 nt
格式说明:词语 词频 词性(可选)
2 基础使用案例
import jieba
# 加载自定义词典
jieba.load_userdict("my_dict.txt")
# 测试文本
text = "我最近在学习自然语言处理和深度学习,对人工智能很感兴趣"
# 使用带自定义词典的分词
words = jieba.lcut(text)
print("分词结果:")
print("/".join(words))
# 输出:
# 我/在/学习/自然语言处理/和/深度学习/,/对/人工智能/很/感兴趣
3 不使用自定义词典的对比
import jieba
# 重置jieba(清空自定义词典)
jieba.initialize()
text = "我最近在学习自然语言处理和深度学习,对人工智能很感兴趣"
# 不使用自定义词典
words = jieba.lcut(text)
print("未使用自定义词典:")
print("/".join(words))
# 输出可能是:
# 我/在/学习/自然语言/处理/和/深度/学习/,/对/人工智能/很/感兴趣
4 动态添加词汇
import jieba
# 方法1:使用add_word()动态添加
jieba.add_word("Transformer", freq=10, tag="n")
jieba.add_word("BERT模型", freq=5)
# 方法2:使用add_word_dict()添加批量词
new_words = {
"注意力机制": 5,
"预训练模型": 5
}
for word, freq in new_words.items():
jieba.add_word(word, freq=freq)
text = "Transformer和BERT模型都是基于注意力机制的预训练模型"
words = jieba.lcut(text)
print("动态添加词汇后:")
print("/".join(words))
5 完整实战案例:医疗文本分词
import jieba
import jieba.posseg as pseg
# 创建医疗词典
medical_dict = """
新型冠状病毒 5 n
临床表现 5 n
核酸检测 5 n
密切接触者 5 n
潜伏期 3 n
发热门诊 5 n
"""
with open("medical_dict.txt", "w", encoding="utf-8") as f:
f.write(medical_dict)
# 加载医疗词典
jieba.load_userdict("medical_dict.txt")
def medical_segmentation(text):
"""
医疗文本分词函数
"""
# 使用词性标注
words = pseg.cut(text)
result = []
for word, flag in words:
result.append(f"{word}/{flag}")
return result
# 测试
medical_text = """
患者前往发热门诊进行核酸检测,临床表现为持续发热和干咳。
密切接触者需要进行14天隔离观察。
"""
print("医疗文本分词结果:")
seg_result = medical_segmentation(medical_text)
print(", ".join(seg_result))
6 调整词典权重
import jieba
# 加载词典
jieba.load_userdict("my_dict.txt")
# 调整词语权重
def adjust_word_weight(word, weight):
"""
调整词语的权重
"""
jieba.del_word(word) # 删除原词
jieba.add_word(word, freq=weight) # 重新添加
# 测试
text = "今天天气很好,适合出去运动"
jieba.add_word("运动", freq=10) # 提高"运动"的权重
jieba.add_word("天气", freq=1) # 降低"天气"的权重
words = jieba.lcut(text)
print("调整权重后:")
print("/".join(words))
7 常见问题处理
import jieba
class CustomDictManager:
"""自定义词典管理器"""
def __init__(self, dict_path=None):
self.dict_path = dict_path
if dict_path:
self.load_dict(dict_path)
def load_dict(self, dict_path):
"""加载自定义词典"""
try:
jieba.load_userdict(dict_path)
print(f"成功加载词典:{dict_path}")
except Exception as e:
print(f"加载词典失败:{e}")
def add_words_from_list(self, word_list):
"""从列表添加词汇"""
for word_info in word_list:
if len(word_info) == 2:
word, freq = word_info
jieba.add_word(word, freq=freq)
elif len(word_info) == 3:
word, freq, pos = word_info
jieba.add_word(word, freq=freq, tag=pos)
def multi_dict_test(self, texts):
"""测试多个文本的分词效果"""
for i, text in enumerate(texts, 1):
print(f"\n测试文本 {i}:")
print(f"原文:{text}")
words = jieba.lcut(text)
print(f"分词:{'/'.join(words)}")
def analyze_error(self, text, correct_seg):
"""分析分词错误"""
my_seg = jieba.lcut(text)
errors = []
for i, (my, correct) in enumerate(zip(my_seg, correct_seg)):
if my != correct:
errors.append(f"位置{i}:我的'{my}',正确'{correct}'")
if errors:
print("分词错误:")
for error in errors:
print(f" - {error}")
else:
print("分词正确!")
# 使用示例
if __name__ == "__main__":
# 创建管理器
manager = CustomDictManager()
# 批量添加词汇
new_words = [
("Python编程", 5, "n"),
("数据分析师", 3, "n"),
("机器学习算法", 5, "n")
]
manager.add_words_from_list(new_words)
# 测试
test_texts = [
"我是一名Python编程数据分析师",
"机器学习算法是人工智能的核心"
]
manager.multi_dict_test(test_texts)
# 分析错误
actual_text = "自然语言处理很有趣"
correct_seg = ["自然语言处理", "很", "有趣"]
manager.analyze_error(actual_text, correct_seg)
注意事项
- 词典格式:UTF-8编码,每行一个词
- 词频设置:词频越高,越容易被识别为独立词
- 词典更新:加载后可以通过
add_word()动态更新 - 性能影响:过大的词典会影响分词速度
最佳实践
import jieba
import os
def setup_custom_dict(dict_dir="dicts"):
"""
设置自定义词典的最佳实践
"""
# 确保目录存在
if not os.path.exists(dict_dir):
os.makedirs(dict_dir)
# 主词典
main_dict = os.path.join(dict_dir, "main_dict.txt")
if os.path.exists(main_dict):
jieba.load_userdict(main_dict)
# 专业词典
for sub_dict in ["tech_dict.txt", "medical_dict.txt", "legal_dict.txt"]:
dict_path = os.path.join(dict_dir, sub_dict)
if os.path.exists(dict_path):
jieba.load_userdict(dict_path)
return jieba
# 使用
jieba = setup_custom_dict()
text = "结合深度学习在医疗领域的应用"
words = jieba.lcut(text)
print("分词结果:", "/".join(words))
这个案例涵盖了自定义词典的创建、加载、动态调整和实际应用场景,可以根据具体需求灵活使用。