一、使用到的依赖库
1.1 pkg_resources库
pkg_resources是一个用于管理Python包和资源的工具,它包含在setuptool库中,可以帮助我们获取包内资源的路径,加载资源文件等等,一般情况下pkg_resources通过setuptools一起安装。
安装setuptools库:
pip install setuptools
有功能:
(1)获取包内文件的路径,resource_filename()
示例:
import pkg_resources
file_path = pkg_resources.resource_filename('my_package', 'data/data.txt')
print(file_path)
包结构如下
my_package/
__init__.py
data/
data.txt
则会输出data.txt 文件的绝对路径my_package/data/data.txt
(2)加载资源文件内容,resource_string()
示例:
import pkg_resources
data = pkg_resources.resource_string('my_package', 'data/data.txt')
print(data.decode('utf-8'))
上述代码则会会打印出utf-8编码的文本文件data.txt 的内容
(3)列出包内所有文件,resource_listdir()
示例:
import pkg_resources
files = pkg_resources.resource_listdir('my_package', 'data')
print(files)
上述代码会列出 data 目录下的所有文件
更多用法参考 Python pkg_resources|极客教程
1.2 symspellpy库
它是一个基于SymSpell算法的快速且准确的拼写纠正器。旨在帮助开发者和用户在文本处理中实现高效的拼写错误检测与修正。
安装symspellpy库:
pip install symspellpy
load_dictionary
加载频率字典文件,字典文件格式为
<term> <count>
<term> <count>
...
<term> <count>
sym_spell.load_dictionary(dictionary_path, term_index=0, count_index=1)
# term_index=0表示第一列为单词 count_index=1表示第二列为单词频率
lookup
查找与输入词相似的词汇
suggestions = sym_spell.lookup(input_term, Verbosity.CLOSEST, max_edit_distance=2)
# Verbosity.CLOSEST表示只返回与输入词编辑距离最近的建议
# max_edit_distance=2表示与输入词的最大编辑距离是2
word_segmentation
把长字符串分割成多个可能的字符串,并在最大编辑距离之内修正
result = sym_spell.word_segmentation(input_term)
# 将一个较长的词或短语分割成可能的单词序列,最终返回的结果有四部分
# result中包含
# 分割后的原字符串segmented_string='in the night i love a boy i miss him everyday'
# 分割并修正的字符串corrected_string='in the night i love a boy i miss him everyday'
# 总编辑距离distance_sum=10
# 对数概率和(越接近0越好)log_prob_sum=-35.55935431828122
更多用法参考 symspellpy:SymSpell Python 移植 — symspellpy 6.7.7 文档
二、导入库
import pkg_resources
from symspellpy.symspellpy import SymSpell
三、初始化SymSpell对象
初始化SymSpell对象,max_dictionary_edit_distance=0将最大编辑距离设置为0,表示只查找完全相同的单词,prefix_length=7表示考虑单词前缀长度为7,查找时会考虑单词的前七个字符
sym_spell = SymSpell(max_dictionary_edit_distance=0, prefix_length=7)
四、加载字典文件
传入字典路径,指定字典文件中第一列是单词,第二列是单词在语料库中的出现频率
dictionary_path = pkg_resources.resource_filename("symspellpy", "frequency_dictionary_en_82_765.txt")
sym_spell.load_dictionary(dictionary_path, term_index=0, count_index=1)
五、分割单词结果
传入长字符串,使用symspell进行单词分割,并输出分词并修正后的句子,总编辑距离以及总对数概率
input_term ="inthenightiloveaboyimisshimeveryday"
result = sym_spell.word_segmentation(input_term)
print(f"分词后句子为:{result.corrected_string}\n总编辑距离为:{result.distance_sum}\n总对数概率为:{result.log_prob_sum}\n")
六、完整代码
import pkg_resources
from symspellpy.symspellpy import SymSpell
sym_spell = SymSpell(max_dictionary_edit_distance=0, prefix_length=7)
dictionary_path = pkg_resources.resource_filename("symspellpy", "frequency_dictionary_en_82_765.txt")
sym_spell.load_dictionary(dictionary_path, term_index=0, count_index=1)
input_term ="inthenightiloveaboyimisshimeveryday"
result = sym_spell.word_segmentation(input_term)
print(f"分词后句子为:{result.corrected_string}\n总编辑距离为:{result.distance_sum}\n总对数概率为:{result.log_prob_sum}\n")