add solution for hw4:3233
This commit is contained in:
11
java/wordStat/WordInfo.java
Normal file
11
java/wordStat/WordInfo.java
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
public class WordInfo {
|
||||||
|
String word;
|
||||||
|
int count;
|
||||||
|
int firstIndex;
|
||||||
|
|
||||||
|
WordInfo(String word, int count, int firstIndex) {
|
||||||
|
this.word = word;
|
||||||
|
this.count = count;
|
||||||
|
this.firstIndex = firstIndex;
|
||||||
|
}
|
||||||
|
}
|
||||||
71
java/wordStat/WordStatLength.java
Normal file
71
java/wordStat/WordStatLength.java
Normal file
@@ -0,0 +1,71 @@
|
|||||||
|
import java.io.*;
|
||||||
|
import java.util.*;
|
||||||
|
|
||||||
|
public class WordStatLength {
|
||||||
|
public static void main(String[] args) {
|
||||||
|
if (args.length != 2) {
|
||||||
|
System.err.println("incorrect input!");
|
||||||
|
System.err.println("usage: java WordStat inputFile outputFile");
|
||||||
|
}
|
||||||
|
|
||||||
|
String inputFileName = args[0];
|
||||||
|
String outputFileName = args[1];
|
||||||
|
try {
|
||||||
|
BufferedReader r = new BufferedReader(new FileReader(inputFileName));
|
||||||
|
|
||||||
|
Map<String, WordInfo> wordMap = new HashMap<>();
|
||||||
|
StringBuilder sb = new StringBuilder();
|
||||||
|
int wordIndex = 0;
|
||||||
|
|
||||||
|
int data = r.read();
|
||||||
|
while (data != -1) {
|
||||||
|
char c = (char) data;
|
||||||
|
|
||||||
|
if (Character.getType(c) == Character.DASH_PUNCTUATION ||
|
||||||
|
Character.isLetter(c) || c == '\'') {
|
||||||
|
sb.append(c);
|
||||||
|
} else {
|
||||||
|
if (sb.length() > 0) {
|
||||||
|
String word = sb.toString().toLowerCase();
|
||||||
|
if (wordMap.containsKey(word)) {
|
||||||
|
wordMap.get(word).count++;
|
||||||
|
} else {
|
||||||
|
wordMap.put(word, new WordInfo(word, 1, wordIndex));
|
||||||
|
wordIndex++;
|
||||||
|
}
|
||||||
|
sb.setLength(0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
data = r.read();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (sb.length() > 0) {
|
||||||
|
String word = sb.toString().toLowerCase();
|
||||||
|
if (wordMap.containsKey(word)) {
|
||||||
|
wordMap.get(word).count++;
|
||||||
|
} else {
|
||||||
|
wordMap.put(word, new WordInfo(word, 1, wordIndex));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
r.close();
|
||||||
|
|
||||||
|
List<WordInfo> sortedWords = new ArrayList<>(wordMap.values());
|
||||||
|
sortedWords.sort(Comparator.comparingInt((WordInfo w) -> w.word.length())
|
||||||
|
.thenComparingInt(w -> w.firstIndex));
|
||||||
|
|
||||||
|
|
||||||
|
PrintWriter writer = new PrintWriter(outputFileName, "UTF-8");
|
||||||
|
|
||||||
|
for (WordInfo info : sortedWords) {
|
||||||
|
writer.println(info.word + " " + info.count);
|
||||||
|
}
|
||||||
|
|
||||||
|
writer.close();
|
||||||
|
|
||||||
|
} catch (Exception ex) {
|
||||||
|
System.err.println("An error occured: " + ex.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user