停用詞表的修改
停用詞表在“pyhanlp\static\data\dictionary”路徑下的“stopwords.txt”文件中,CoreStopWordDictionary.apply方法支持去除停用詞。如果需要修改停用詞表,則直接編輯文件“stopwords.txt”,之后刪除路徑下的“stopwords.txt.bin”,運行CoreStopWordDictionary.apply后即可自動生效。有關驗證的方法見“驗證是否生效”小節。
自定義詞語過濾方法
用戶可以通過編寫“pyhanlp\static”路徑下的“MyFilter.java”文件設置自己的詞語過濾方法。應當注意這里處理的語言單位是詞語,而不是字。編輯完畢后需要編譯該文件並生成字節碼文件,之后運行CoreStopWordDictionary.apply方法時就會自動調用用戶自己的詞語過濾方法了。這里給出一個自定義過濾方法的編寫示例代碼。
import os
from pyhanlp.static import STATIC_ROOT, HANLP_JAR_PATH
java_code_path = os.path.join(STATIC_ROOT, 'MyFilter.java')
with open(java_code_path, 'w') as out:
java_code = """
import com.hankcs.hanlp.dictionary.stopword.CoreStopWordDictionary;
import com.hankcs.hanlp.dictionary.stopword.Filter;
import com.hankcs.hanlp.seg.common.Term;
public class MyFilter implements Filter
{
public boolean shouldInclude(Term term)
{
if (term.nature.startsWith('m')) return false; // 數詞過濾
if (term.nature.startsWith('q')) return false; // 量詞過濾
if (term.nature.startsWith('t')) return false; // 時間詞過濾
if (term.nature.startsWith("w")) return false; // 過濾標點符號
return !CoreStopWordDictionary.contains(term.word); // 停用詞過濾
}
}
"""
out.write(java_code)
os.system('javac -cp {} {} -d {}'.format(HANLP_JAR_PATH, java_code_path, STATIC_ROOT))
驗證是否生效
本節給出停用詞表修改后以及使用了自定義詞語過濾方法的示例代碼。
from pyhanlp import *
# 加載停用詞類
CoreStopWordDictionary = JClass("com.hankcs.hanlp.dictionary.stopword.CoreStopWordDictionary")
# 加載自定義詞語過濾邏輯
MyFilter = JClass('MyFilter')
CoreStopWordDictionary.FILTER = MyFilter()
term_list = HanLP.segment(text)
CoreStopWordDictionary.apply(term_list)