2011-07-25 43 views
3

所以我使用的Weka機器學習庫的Java API和我有以下代碼:的Java秧雞stringtowordvector不計字OCCURENCES正確

String html = "repeat repeat repeat"; 

    Attribute input = new Attribute("html",(FastVector) null); 

    FastVector inputVec = new FastVector(); 
    inputVec.addElement(input); 

    Instances htmlInst = new Instances("html",inputVec,1); 
    htmlInst.add(new Instance(1)); 
    htmlInst.instance(0).setValue(0, html); 

    StringToWordVector filter = new StringToWordVector(); 
    filter.setUseStoplist(true); 

    filter.setInputFormat(htmlInst); 
    Instances dataFiltered = Filter.useFilter(htmlInst, filter); 

    Instance last = dataFiltered.lastInstance(); 
    System.out.println(last); 

雖然StringToWordVector應該在字符串中數字出現次數,而不是「重複」一詞計數3次,計數僅作爲1發生1

我在做什麼錯了?

回答

0

哎...所有這些代碼行。這幾條線怎麼樣呢?

public static Map<String, Integer> countWords(String input) { 
    Map<String, Integer> map = new HashMap<String, Integer>(); 
    Matcher matcher = Pattern.compile("\\b\\w+\\b").matcher(input); 
    while (matcher.find()) 
     map.put(matcher.group(), map.containsKey(matcher.group()) ? map.get(matcher.group()) + 1 : 1); 
    return map; 
} 

下面的代碼中的操作:

public static void main(String[] args) { 
    System.out.println(countWords("sample, repeat sample, of text")); 
} 

輸出:

{of=1, text=1, repeat=1, sample=2} 
6

的默認設置是僅報告存在/不存在爲0/1。您必須明確啓用計數。添加:

filter.setOutputWordCounts(true);

並重新運行。

Weka有一個明確的郵件列表;在那裏發佈這樣的問題可能會給你更快的迴應