0

複数のファイルから単語の出現頻度をカウントしたい。

さらに、これらのファイルにはこれらの単語があります

a1.txt = {aaa, aaa, aaa} 
a2.txt = {aaa} 
a3.txt = {aaa, bbb} 

したがって、結果は aaa = 3、bbb = 1 でなければなりません。

次に、上記のデータ構造を定義しました。

LinkedHashMap<String, Integer> wordCount = new LinkedHashMap<String, Integer>();
Map<String, LinkedHashMap<String, Integer>>
fileToWordCount = new HashMap<String,LinkedHashMap<String, Integer>>();

次に、ファイルから単語を読み取り、wordCount と fileToWordCount に入れます。

/*lineWords[i] is a word from a line in the file*/
if(wordCount.containsKey(lineWords[i])){
   System.out.println("1111111::"+lineWords[i]);
   wordCount.put(lineWords[i], wordCount.
   get(lineWords[i]).intValue()+1);
   }else{
   System.out.println("222222::"+lineWords[i]);
   wordCount.put(lineWords[i], 1);
}
fileToWordCount.put(filename, wordCount); //here we map filename
and occurences        of       words

最後に、上記のコードで fileToWordCount を出力します。

Collection a;
Set filenameset;

        filenameset = fileToWordCount.keySet();    
        a = fileToWordCount.values();          
        for(Object filenameFromMap: filenameset){
                   System.out.println("FILENAMEFROMAP::"+filenameFromMap);                                 
                System.out.println("VALUES::"+a);                                                
        }

そして版画、

FILENAMEFROMAP::a3.txt
VALUES::[{aaa=5, bbb=1}, {aaa=5, bbb=1}, {aaa=5, bbb=1}]
FILENAMEFROMAP::a1.txt
VALUES::[{aaa=5, bbb=1}, {aaa=5, bbb=1}, {aaa=5, bbb=1}]
FILENAMEFROMAP::a2.txt
VALUES::[{aaa=5, bbb=1}, {aaa=5, bbb=1}, {aaa=5, bbb=1}]

では、マップ fileToWordCount を使用して、ファイル内の単語の頻度を見つけるにはどうすればよいでしょうか?

4

2 に答える 2

1

あなたはそれを必要以上に難しくしています。これが私がそれを行う方法です:

Map<String, Counter> wordCounts = new HashMap<String, Counter>();
for (File file : files) {
    Set<String> wordsInFile = new HashSet<String>(); // to avoid counting the same word in the same file twice
    for (String word : readWordsFromFile(file)) {
        if (!wordsInFile.contains(word)) {
            wordsInFile.add(word);
            Counter counter = wordCounts.get(word);
            if (counter == null) {
                counter = new Counter();
                wordCounts.put(word, counter);
            }
            counter.increment();
        }
    }
}
于 2012-11-25T09:25:25.093 に答える
0

別のアプローチを提案する場合:)

を使用しMap<String, Set<String>> mapます。

foreach file f in files
  foreach word w in f
    if w in map.keys()
      map[w].add(f)
    else
      initialize map w to be a set with the only element file
于 2012-11-25T09:26:54.903 に答える