由於在一些場景中,所有的字母都連在了一起,所以我們需要將字母分割成單詞的形式。
1. 安裝
pip install -U symspellpy
2. 下載詞典
curl -LJO https://raw.githubusercontent.com/mammothb/symspellpy/master/symspellpy/frequency_dictionary_en_82_765.txt
curl -LJO https://raw.githubusercontent.com/mammothb/symspellpy/master/symspellpy/frequency_bigramdictionary_en_243_342.txt
如果下載不了的話,也可以在CSDN上進行下載,鏈接爲https://download.csdn.net/download/herosunly/12326704。
3. 單詞分割
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)
# a sentence without any spaces
input_term = "thequickbrownfoxjumpsoverthelazydog"
result = sym_spell.word_segmentation(input_term)
print("{}, {}, {}".format(result.corrected_string, result.distance_sum,
result.log_prob_sum))
需要注意的是distance_sum的範圍爲[0, len(input_term)],其中0表示input_term就是一個單詞,而len(input_term)表示該單詞無法進行劃分。