本期圍繞jieba講一個我遇到的實際問題,在同一個服務(wù)里,存在兩個不同接口A和B,都用到了jieba分詞,區(qū)別在于兩者需要調(diào)用不同的詞庫,巧合中,存在以下情況:
詞庫A:"干拌面"
詞庫B:"干拌","面"
在服務(wù)啟動的時候,由于詞庫A優(yōu)先被加載了,再去加載詞庫B的時候發(fā)現(xiàn),并沒有加載成功:
接口A中:
jieba.load_userdict("A.txt")
接口B中:
jieba.load_userdict("B.txt")
結(jié)果發(fā)現(xiàn),在切干拌面這個詞的時候,接口B中還是沒有切成功。其實每次在我們加載jieba的時候,可以注意一下會出現(xiàn)以下info:
Building prefix dict from the default dictionary ...
Dumping model to file cache /var/folders/hv/kfb7n4lj06590hqxjv6f3dd00000gn/T/jieba.cache
Loading model cost 0.824 seconds.
Prefix dict has been built succesfully.
顯而易見,先進(jìn)行了Building prefix dict,再Dumping model to file cache,后續(xù)Loading model都會來自這,所以這個地方導(dǎo)致以上問題。
我是這么處理的:
接口A中:
jieba1 = jieba.Tokenizer(dictionary="A.txt")
接口B中:
jieba2 = jieba.Tokenizer(dictionary="B.txt")
案例如下:
In [1]: import jieba
In [2]: jieba1=jieba.Tokenizer(dictionary="A.txt")
In [3]: jieba2=jieba.Tokenizer(dictionary="B.txt")
In [4]: jieba1.lcut("干拌面")
Building prefix dict from /Users/slade/Desktop/A.txt ...
Dumping model to file cache /var/folders/hv/kfb7n4lj06590hqxjv6f3dd00000gn/T/jieba.u5221c1b70f06b36e44bc519f39715c96.cache
Loading model cost 0.006 seconds.
Prefix dict has been built succesfully.
Out[4]: ['干拌面']
In [5]: jieba2.lcut("干拌面")
Building prefix dict from /Users/slade/Desktop/B.txt ...
Dumping model to file cache /var/folders/hv/kfb7n4lj06590hqxjv6f3dd00000gn/T/jieba.uc4f38d90bf7ce748744ff94fb2863fe4.cache
Loading model cost 0.003 seconds.
Prefix dict has been built succesfully.
Out[5]: ['干拌', '面']
需要注意的是,去看Tokenizer源碼,里面有這么一段讀取調(diào)用:
def gen_pfdict(self, f):
lfreq = {}
ltotal = 0
f_name = resolve_filename(f)
for lineno, line in enumerate(f, 1):
try:
line = line.strip().decode('utf-8')
word, freq = line.split(' ')[:2]
freq = int(freq)
lfreq[word] = freq
ltotal += freq
for ch in xrange(len(word)):
wfrag = word[:ch + 1]
if wfrag not in lfreq:
lfreq[wfrag] = 0
except ValueError:
raise ValueError(
'invalid dictionary entry in %s at Line %s: %s' % (f_name, lineno, line))
f.close()
return lfreq, ltotal
在load_userdict的時候詞庫的詞頻可以省略不寫,word, freq = line.split(' ')[:2]決定了這邊需要加上,這個依賴于版本,我并沒有實驗不同版本。
A.txt:
干拌面 1
B.txt:
干拌 1
面 1
歡迎大家關(guān)注我的個人bolg,知乎,更多代碼內(nèi)容歡迎follow我的個人Github,如果有任何算法、代碼、轉(zhuǎn)行疑問都?xì)g迎通過郵箱發(fā)消息給我。