2010-10-13 57 views
1

我想在lucene項目中使用WikipediaTokenizer - http://lucene.apache.org/java/3_0_2/api/contrib-wikipedia/org/apache/lucene/wikipedia/analysis/WikipediaTokenizer.html但我從未使用過lucene。我只是想將一個維基百科字符串轉換爲一個令牌列表。但是,我發現在這個類中只有四種方法可用,end,incrementToken,reset,reset(reader)。有人能給我一個例子來使用它。在Lucene中使用WikipediaTokenizer的示例

謝謝。

+0

參見http://stackoverflow.com/questions/3916806/3916947#3916947 – 2010-10-15 12:52:26

回答

3

在Lucene的3.0,next()方法被移除。現在您應該使用incrementToken來遍歷令牌,並且當您到達輸入流的末尾時它將返回false。要獲得每個令牌,您應該使用AttributeSource類的方法。根據您想要獲得的屬性(術語,類型,有效載荷等),您需要使用addAttribute方法將相應屬性的類類型添加到您的標記器。

以下部分代碼示例來自WikipediaTokenizer的測試類,如果您下載Lucene的源代碼,您可以找到它。

... 
WikipediaTokenizer tf = new WikipediaTokenizer(new StringReader(test)); 
int count = 0; 
int numItalics = 0; 
int numBoldItalics = 0; 
int numCategory = 0; 
int numCitation = 0; 
TermAttribute termAtt = tf.addAttribute(TermAttribute.class); 
TypeAttribute typeAtt = tf.addAttribute(TypeAttribute.class); 

while (tf.incrementToken()) { 
    String tokText = termAtt.term(); 
    //System.out.println("Text: " + tokText + " Type: " + token.type()); 
    String expectedType = (String) tcm.get(tokText); 
    assertTrue("expectedType is null and it shouldn't be for: " + tf.toString(), expectedType != null); 
    assertTrue(typeAtt.type() + " is not equal to " + expectedType + " for " + tf.toString(), typeAtt.type().equals(expectedType) == true); 
    count++; 
    if (typeAtt.type().equals(WikipediaTokenizer.ITALICS) == true){ 
    numItalics++; 
    } else if (typeAtt.type().equals(WikipediaTokenizer.BOLD_ITALICS) == true){ 
    numBoldItalics++; 
    } else if (typeAtt.type().equals(WikipediaTokenizer.CATEGORY) == true){ 
    numCategory++; 
    } 
    else if (typeAtt.type().equals(WikipediaTokenizer.CITATION) == true){ 
    numCitation++; 
    } 
} 
... 
0

公共類WikipediaTokenizerTest { 靜態記錄器記錄器= Logger.getLogger(WikipediaTokenizerTest.class); protected static final String LINK_PHRASES =「單擊[[here here again]]點擊[http://lucene.apache.org here] [[Category:a b c d]]」;

public WikipediaTokenizer testSimple() throws Exception { 
    String text = "This is a [[Category:foo]]"; 
    return new WikipediaTokenizer(new StringReader(text)); 
} 
public static void main(String[] args){ 
    WikipediaTokenizerTest wtt = new WikipediaTokenizerTest(); 

    try { 
     WikipediaTokenizer x = wtt.testSimple(); 

     logger.info(x.hasAttributes()); 

     Token token = new Token(); 
     int count = 0; 
     int numItalics = 0; 
     int numBoldItalics = 0; 
     int numCategory = 0; 
     int numCitation = 0; 

     while (x.incrementToken() == true) { 
      logger.info("seen something"); 
     } 

    } catch(Exception e){ 
     logger.error("Exception while tokenizing Wiki Text: " + e.getMessage()); 
    } 


} 
+0

TermAttribute不Lucene的4.2.1可用。那麼,如何在移植到更高版本的Lucene時訪問這些屬性? – RalfB 2014-05-30 08:09:25