2015-05-29 80 views
13

有很多的例子,說明如何使用StandardTokenizer這樣的:如何使用StandardTokenizer從Lucene的5.x.x

TokenStream tokenStream = new StandardTokenizer(
      Version.LUCENE_36, new StringReader(input)); 

但在新版本的Lucene這個構造是不可用的。新的構造是這樣的:

StandardTokenizer(AttributeFactory factory) 

這是什麼AttributeFactory的角色,我怎麼能在標記化的Lucene的新版本字符串?

+0

你試過路過的單身'AttributeFactory.DEFAULT_ATTRIBUTE_FACTORY'?或者使用無參數構造函數? – sisve

+1

嗨西蒙感謝提示。它可以處理這個代碼: Tokenizer tokenStream = new StandardTokenizer(); tokenStream.setReader(new StringReader(input)); 當你應用你的過濾器時,你會得到一個TokenStream。 TokenStream的工作流程也發生了變化,您現在需要調用reset();在開始使用此流之前。 – samy

+0

這個問題的答案呢? – soulcheck

回答

17

AttributeFactory創建AttributeImpl s,它們是Attribute s的來源。屬性控制TokenStream的行爲,這是用於讀取/跟蹤StandardTokenizer的數據流的基礎機制。

小已從4.x的改變相對於該AttributeFactory到5.x - 兩個版本中,您可以創建一個StandardTokenizerAttributeFactory,如果你願意,或者如果你不指定一個,然後AttributeFactory.DEFAULT_ATTRIBUTE_FACTORY最終會被使用。

最大的區別是你也可以在輸入流中傳入Reader作爲構造函數的一部分。這意味着在4.x中,您將不得不爲每個想要處理的輸入流創建一個新的StreamTokenizer,而這又必須重新初始化AttributeFactory中的屬性。

我不是Lucene的開發者,但我的猜測是,這只是一個重組,鼓勵在多個流的閱讀中重用屬性。如果您看看TokenStream的內部結構和默認的AttributesFactory實現,那麼創建和設置屬性會涉及很多反射。如果我不得不猜測,剛剛刪除了帶讀者的構造函數,以鼓勵重用標記器及其屬性,因爲這些屬性的初始化相對昂貴。

編輯

添加一個期待已久的例子 - 抱歉,沒有這個領導:

// Define your attribute factory (or use the default) - same between 4.x and 5.x 
AttributeFactory factory = AttributeFactory.DEFAULT_ATTRIBUTE_FACTORY; 

// Create the tokenizer and prepare it for reading 
// Lucene 4.x 
StandardTokenizer tokenizer = 
     new StandardTokenizer(factory, new StringReader("Tokenize me!")); 
tokenizer.reset(); 
// Lucene 5.x 
StandardTokenizer tokenizer = new StandardTokenizer(factory); 
tokenizer.setReader(new StringReader("Tokenizer me!")); 
tokenizer.reset(); 

// Then process tokens - same between 4.x and 5.x 
// NOTE: Here I'm adding a single expected attribute to handle string tokens, 
// but you would probably want to do something more meaningful/elegant 
CharTermAttribute attr = tokenizer.addAttribute(CharTermAttribute.class); 
while(tokenizer.incrementToken()) { 
    // Grab the term 
    String term = attr.toString(); 

    // Do something crazy... 
} 
+0

我想向@RustyBuckets提供我的賞金,我該如何做? – Filip

+0

@Filip我猜它已經太晚了,我只是今天看到了答案。 RustyBuckets感謝您的解釋,也許您還可以添加一個簡單的代碼示例,瞭解如何使用新的StandardTokenizer,我認爲它可以幫助一些人。我目前正在使用它: Tokenizer source = new StandardTokenizer(); source.setReader(new StringReader(mytext)); – samy

+0

是的PLZ,作爲一個例子的代碼片段將是非常有用的 – higuaro