I need to create a program that can: 1. Read from a txt file. 2. A struct that c
ID: 3798809 • Letter: I
Question
I need to create a program that can:
1. Read from a txt file.
2. A struct that consists of: "string value" and "int freq";
3. Tokenize each word in that txt file.
4. Store each token(struct) into a vector made of structs.
5. Also store each token's frequency count in the struct.
6. Insertion sort the vector from A to Z.
7. Write back to the file.
7. Print out everything in the vector/file. (Each word/token and its freq count).
Output should look like:
[('no,', 1), ('and', 1), ('walking', 1), ('be', 1), ('dictionary.', 1), ('Bjarne', 1), ('all', 1), ('need', 1), ('Stroustrup', 1), ('at', 1), ('times.', 1), ('programmer.', 1), ('where', 1), ('find', 1), ('that,', 1), ('would', 1), ('when', 1), ('detail', 1), ('time,', 1), ('to', 1), ('much', 1), ('details', 1), ('main', 1), ('C++', 1), ('poorer', 1), ('most', 1), ('every', 1), ("I'm", 1), ('by', 1), ('And', 1), ('did', 1), ('of', 1), ('straight', 1), ('know', 1), ('technical', 1), ('points', 1), ('them.', 1), ('If', 1), ('in', 2), ('head', 2), ('a', 2), ('not', 2), ('keep', 2), ('my', 2), ('do', 3), ('the', 3), ('I', 6)]
Explanation / Answer
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.util.Scanner;
import java.util.TreeMap;
class Token {
private String value;
private int frequency;
public Token(String value, int frequency) {
super();
this.value = value;
this.frequency = frequency;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public int getFrequency() {
return frequency;
}
public void setFrequency(int frequency) {
this.frequency = frequency;
}
@Override
public String toString() {
return "(" + this.value + "," + this.frequency + ")";
}
}
public class Chegg_27_02_2017_03 {
public static void main(String[] args) {
TreeMap<String, Token> container = new TreeMap<>();
try (Scanner sc = new Scanner(new File("ValenciaCourses.txt"));
BufferedWriter out = new BufferedWriter(new FileWriter("OutputFile.txt"));) {
while (sc.hasNextLine()) {
String aLine = sc.nextLine();
String words[] = aLine.split(" ");
for (String word : words) {
if (word.matches("\s*"))
continue;
if (container.containsKey(word)) {
Token temp = container.get(word);
temp.setFrequency(temp.getFrequency() + 1);
} else {
container.put(word, new Token(word, 1));
}
}
}
out.write(container.values().toString());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.