IK中文分詞擴展自定義詞典!!!

1.基於分佈式系統的自定義分詞要求與流程設計
  (見圖)E:\plan\readingnote\分詞與索引\分詞\2012-4-20
2.分詞實現原理——詞典的加載過程
  2.1.分詞詞典的加載過程涉及到3個類,分別是Configuration類,Directory類,以及DictSegment類。
其中前兩個類是獲得配置文件,獲得分詞詞典的,爲詞典內容的加載做準備的。而DictSegment類則是實現真正的分詞加載的類。
 2.2.在調用分詞的過程中,首先調用Directory類對象,在方法loadMainDict()中,包含了自定義分詞詞典內容的加載。
  2.2.1.在自定義分詞內容的加載中,首先調用Configuration類中的一個方法,用來獲得IKAnalyzer.cfg.xml(自定義詞典文件配置路徑)中配置的自定義詞典文件的配置路徑。List<String> extDictFiles  = Configuration.getExtDictionarys();在這之前,得先獲得配置文件的路徑,並將其作爲流加載到內存中。其實,這兩件事情都是在Configuration類中實現的,Directory類只是調用了Configuration類提供的接口而已。
  2.2.2.現在來看看Configuration類中做的兩件事。
private Configuration(){
props = new Properties();
// String path=Configuration.class.getResource(FILE_NAME).toString();
// String path2=Configuration.class.getResource("").toString();
// String path3=Configuration.class.getResource("/").toString();
InputStream input = Configuration.class.getResourceAsStream(FILE_NAME);
if(input != null){
try {
props.loadFromXML(input);
} catch (InvalidPropertiesFormatException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
  (1)初始化。將IKAnalyzer.cfg.xml作爲流加載到內存中。注意加粗的代碼,這就使得在不修改代碼的情況下,只能加載到類所在的classpath路徑下的文件。(對於加粗代碼的理解,詳見E:\plan\readingnote\分詞與索引\分詞\分詞自定義詞典路徑
  public static List<String> getExtDictionarys(){
List<String> extDictFiles = new ArrayList<String>(2);
String extDictCfg = CFG.props.getProperty(EXT_DICT);
if(extDictCfg != null){
//使用;分割多個擴展字典配置
String[] filePaths = extDictCfg.split(";");
if(filePaths != null){
for(String filePath : filePaths){
if(filePath != null && !"".equals(filePath.trim())){
extDictFiles.add(filePath.trim());
//System.out.println(filePath.trim());
}
}
}
}
return extDictFiles;
}
(2)該段代碼用來實現從IKAnalyzer.cfg.xml中獲取自定義詞典配置路徑,並將其放入一個集合中,作爲返回值返回。
2.2.3現在轉回到Directory類。在獲得自定義詞典文件路徑之後,就是根據文件路徑找到自定義詞典,然後調用DircSegment加載到內村中。
List<String> extDictFiles  = Configuration.getExtDictionarys();
if(extDictFiles != null){
for(String extDictName : extDictFiles){
//讀取擴展詞典文件
is = Dictionary.class.getResourceAsStream(extDictName);
//如果找不到擴展的字典,則忽略
if(is == null){
continue;
}
try {
BufferedReader br = new BufferedReader(new InputStreamReader(is , "UTF-8"), 512);
String theWord = null;
do {
theWord = br.readLine();
if (theWord != null && !"".equals(theWord.trim())) {
//加載擴展詞典數據到主內存詞典中
//System.out.println(theWord);
_MainDict.fillSegment(theWord.trim().toCharArray());
}
} while (theWord != null);
} catch (IOException ioe) {
System.err.println("Extension Dictionary loading exception.");
ioe.printStackTrace();
}finally{
try {
if(is != null){
                   is.close();
                   is = null;
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
注意到粗體部分,這就要求其只能獲得Directory類所在的classpath路徑下的資定義詞典文件,超出了這個路徑範圍這找不到了。第二個粗體部分則是調用DictSegment對自定義詞典中的詞進行加載。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章