簡體   English   中英

Java單詞計數器

[英]Java word counter

我在計算Java中的單詞數時遇到一個問題。

我有地圖

Map<String,StringBuilder> files_and_text = new TreeMap<String,StringBuilder>();

String是文件名,而StringBuilder包含文件文本。

例如

StringBuilder file_tex = new StringBuilder();
StringBuilder file_tex2 = new StringBuilder();

file_text.append("some contents some file one");
files_and_tex.put("file1", file_text);

file_text2.append("test words test test words");    
files_and_tex.put("file2", file_text2);

現在,我想制作一本可以告訴我的字典:

         |word 1 | word 2 | word 3 ........
file 1   | 3     |    1   |  0 .........
file 2   | 6     |    2   |  9 .........
.......
.......

單詞1、2、3等是語料庫單詞。 文件1、2、3等是文件名。 該矩陣中的每個值表示該單詞在當前文件中出現的時間。

我最近從C轉到Java,我知道如何編寫混亂的代碼(結構化)來解決此問題; 我想知道如何以純面向對象的方式做到這一點,尤其是在Java中。

注意:這不是作業!

Google的Guava庫提供了一些非常有用的實用程序和數據結構來解決此類問題。

要將文件拆分為單詞,可以使用Splitter:

Iterable<String> wordsInFile = 
   Splitter.on(' ').trimResuls().omitEmptyStrings().split(fileAsString);

要計算給定單詞的出現次數,可以使用多重集:

Multiset<String> countOfEachWord = HashMultiset.create();
countOfEachWord.addAll(wordsInFile);

您可以基於這兩部分來創建某種對象,例如WordLookupTable。 即:

public class WordLookupTable {

  private static final Splitter SPLITTER = Splitter.on(' ').trimResults().omitEmptyStrings();  
  private final Map<String, Multiset<String>> filenameToWordCountSet = Maps.newHashMap();

  public void addFile(String filename, String fileText) {
    Multiset<String> wordsInFile = getWordSetForFile(filename);

    for (String word : SPLITTER.split(fileText)) {
      wordsInFile.add(word);

    }
  }

  // Gets the count of all words for the file
  public long getCountOfWordsForFile(String filename) {
    return getWordSetForFile(filename).size();  

  }

  public long getCountOfWordInFile(String filename, String word) {
    return getWordSetForFile(filename).count(word);
  }

  public long getCountOfWordOverAllFiles(String word) {
    long count = 0;
    for (Multiset<String> wordSet : filenameToWordCountSet.values()) {
      count += wordSet.count(word);
    }
    return count;
  }

  private Multiset<String> getWordSetForFile(String filename) {
    Multiset<String> wordsInFile = filenameToWordCountSet.get(filename);
    if(wordsInFile == null) {
      wordsInFile = HashMultiset.create();
      filenameToWordCountSet.put(filename, wordsInFile);
    }
    return wordsInFile;
  }
}

有很多方法可以做到這一點,讓我向您解釋一種既有效又易於理解的方法。當然,還有面向對象。

[步驟1]您必須有兩個映射,一個映射用於存儲文件特定數據,另一個映射用於存儲文件名和文件數據。 除了文件名,您可以選擇任何內容。

private static HashMap<String, MutableInt> wordMap1 = new HashMap<String, MutableInt>();
private static HashMap<String, MutableInt> wordMap2 = new HashMap<String, MutableInt>();
private static HashMap<String, HashMap> fileMap = new HashMap<String, HashMap>();

[步驟2]設置MutableInt類(從技術上講,您首先要這樣做),現在您可能會問什么是MutableInt,它將創建一個類,以便在遇到給定單詞時可以增加其值。

這是MutableInt類的示例:

class MutableInt {
    int value = 1;
    public void increase () { ++value; }
    public int getValue () { return value; }
    public String toString(){
        return Integer.toString(value);
    }
}

[步驟3]現在,對給定文件中的每個單詞執行以下操作:

  1. 為您正在解析的文件創建一個新的wordMap
  2. 從文件中得到單詞
  3. 使用wordmap.get(“ word”)檢查單詞是否在wordMap中;
  4. 如果輸出為null,則您知道它的新詞。
  5. 將單詞放入地圖中,然后使用以下命令將MutableInt放入其值中
  6. wordmap.put('word“,new MutableInt());
  7. 如果輸出不為null,則說明它不是一個新單詞,因此請使用wordMap.getValue(“ word).increase();增加計數器。
  8. 使用文件中的所有單詞完成此操作后,您想使用fileMap.put(“ filename”,wordMap);將wordMap放入fileMap中。

這是一個示例,應該可以幫助您:

Map<String, StringBuilder> files_and_tex = new HashMap<String, StringBuilder>();

StringBuilder file_text = new StringBuilder();
StringBuilder file_text2 = new StringBuilder();
file_text.append("some contents some file one");
files_and_tex.put("file1", file_text);

file_text2.append("test words test test words");    
files_and_tex.put("file2", file_text2);

// Maps from file-name to word to count
Map<String, Map<String, Integer>> wordCounts =
        new HashMap<String, Map<String, Integer>>();

// Go through each filename (key in files_and_tex)
for (String file : files_and_tex.keySet()) {

    // Create a map to keep track of word counts for this file
    Map<String, Integer> wc = new HashMap<String, Integer>();
    wordCounts.put(file, wc);

    Scanner s = new Scanner("" + files_and_tex.get(file));
    while (s.hasNext()) {
        String word = s.next();
        if (!wc.containsKey(word))
            wc.put(word, 0);
        wc.put(word, wc.get(word) + 1);
    }
}

// And here is how to access the resulting data
System.out.println(wordCounts.get("file1").get("file")); // prints 1
System.out.println(wordCounts.get("file2").get("test")); // prints 3

順便說一句,Java約定建議使用駝峰樣式的標識符。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM