[英]Hashmap Entries don't get into Columns
package einlesen;
/**
* @author a
*
*/
import java.io.*;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Scanner;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTable;
import javax.swing.RowSorter;
import javax.swing.SortOrder;
import javax.swing.WindowConstants;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;
public class Einlesen {
/**
* @param args
* @throws IOException
*/
static List<String> word = new ArrayList<String>();
static Map<String, Integer> wordsInTheMiddle = new HashMap<>();
@SuppressWarnings({ "resource" })
public static void main(String[] args) throws IOException {
Scanner scan = new Scanner(System.in);
String antwort;
System.out.println("Welches Dokument wollen Sie? Geben Sie dabei den Path an, bitte.");
antwort = ("Downloads/lol.txt"); // scan.nextLine();
String path = System.getProperty("user.home");
// System.out.println(path);
File file = Paths.get(path, antwort).toFile();
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
Scanner sc = new Scanner(br);
//List<String> word = new ArrayList<String>();
while (sc.hasNext()) {
String wort = sc.next();
// Remove quotes
if (wort.startsWith("\"")) {
wort = wort.substring(1);
}
if (wort.endsWith("\"")) {
wort = wort.substring(0, wort.length() - 1);
}
word.add(wort);
}
br.close();
int chunkStartIndex = 0;
Map<String, Integer> wordsInTheMiddle = new HashMap<>();
while (word.size() - chunkStartIndex > 0) {
int chunkEndIndex = chunkStartIndex + 2000;
if (chunkEndIndex > word.size()) {
chunkEndIndex = word.size();
}
List<String> chunkOfWords = word.subList(chunkStartIndex, chunkEndIndex);
for (int i = 0; i < chunkOfWords.size(); i++) {
String word1 = chunkOfWords.get(i);
if (word1.matches("[A-Z][a-z][a-z]\\w+")) {
wordsInTheMiddle.putIfAbsent(word1, 0);
int oldCount = wordsInTheMiddle.get(word1);
wordsInTheMiddle.put(word1, oldCount + 1);
}
}
// do not process the last word! Would cause an index out of bounds exception.
for (int i = 0; i < chunkOfWords.size() - 1; i++) {
String word1 = chunkOfWords.get(i);
if (word1.matches("\\w*(\\.|\\?|!)$")) {
// Word is at end of sentence
String nextWord = chunkOfWords.get(i + 1);
if (wordsInTheMiddle.getOrDefault(nextWord, 0) < 2) {
// sort out words that appear at the beginning of a sentence and appear less
// than 2 times in the text
wordsInTheMiddle.remove(nextWord);
}
}
}
// remove blacklisted words
String[] blacklist = { "This", "When", "Night", "Most", "Stone", "There", "Bonfire", "Tuesday", "Their",
"They", "Professor", "Famous", "About", "Madam", "Nearly", "Aunt", "What", "Uncle", "Mommy",
"Scars", "Scotch", "Every", "That" };
for (String listedWord : blacklist) {
wordsInTheMiddle.remove(listedWord);
}
System.out.println("Mitte: " + wordsInTheMiddle);
chunkStartIndex = chunkEndIndex;
}
JTable t = new JTable(toTableModel(wordsInTheMiddle));
TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(t.getModel());
t.setRowSorter(sorter);
List<RowSorter.SortKey> sortKeys = new ArrayList<>(25);
sortKeys.add(new RowSorter.SortKey(1, SortOrder.DESCENDING));
sorter.setSortKeys(sortKeys);
JPanel p = new JPanel();
p.add(t);
JFrame f = new JFrame();
f.add(p);
f.setSize(700, 600);
f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
f.setVisible(true);
f.setTitle(antwort);
}
public static TableModel toTableModel(Map<?, ?> map) {
DefaultTableModel model = new DefaultTableModel(new Object[] { "Key", "Value" }, 0);
for (Map.Entry<?, ?> entry : map.entrySet()) {
model.addRow(new Object[] { entry.getKey(), entry.getValue() });
for (int a = word.size()/2000;model.getColumnCount() - 2 <= a;)
{
model.addColumn(new Object[] { wordsInTheMiddle});
}
}
return model;
}
}
因此,這是我的程序代碼,該程序將文本分為2000個單詞的不同部分,並計算不同部分中名稱的出現率。 這是在Hashmap中完成的。 因此,我需要一個用於該哈希圖的表,在其中可以看到名稱,總計數和每個零件的計數。 第一列是名稱,第二列是總數,其余部分是不同的部分。
像這樣:
name | total count | 1.Part | 2.Part...
---------------------------------------
name | namecounttotal| count1.Part| count2.Part...
我得到了前兩列具有正確條目的信息,但是在其余各列中,我都無法輸入值。 我希望你能幫助我。
您的程序中存在兩個問題:
List<Map<String,Integer>>
或其他數據類型來解決此問題。 在我的示例中,列表的每個元素都將跟蹤該特定塊中的名稱及其數量。 tableToModel()
確實使用.addColumn()
為2,000個單詞塊添加了新列。 但是,當您使用.addRow(Object[])
添加一行時,Object數組僅包含兩個元素。 您需要以某種方式將特定於塊的計數包裝到該Object數組中。 此外,首先使用.addColumn()
創建列,然后再一次添加新行可能是合理的。 我將采取以下措施解決這些問題:
將數據添加到特定於塊的計數器,並跟蹤塊的編號:
List<Map<String,Integer>> wordsPerChunck = new ArrayList<>(); while (word.size() - chunkStartIndex > 0) { // Initialize a chunck-specific word counter Map<String, Integer> countInChunck = new HashMap<>(); wordsPerChunck.add(countInChunck); ... for (int i = 0; i < chunkOfWords.size(); i++) { String word1 = chunkOfWords.get(i); if (word1.matches("[AZ][az][az]\\\\w+")) { wordsInTheMiddle.putIfAbsent(word1, 0); wordsInTheMiddle.put(word1, oldCount + 1); countInChunck.putIfAbsent(word1, 0); // Increase the count in this chunck countInChunck.put(word1, countInChunck.get(word1) + 1); } }
toTableModel
修改toTableModel
:將列表作為第二個參數。 首先創建列,然后創建一個正確大小的Object
數組,該數組包含名稱,總計數和特定於塊的計數:
public static TableModel toTableModel(Map<?, ?> map, List<?> list) { DefaultTableModel model = new DefaultTableModel(new Object[] { "Key", "Value" }, 0); for (Map.Entry<?, ?> entry : map.entrySet()) { for (int a = word.size()/2000; model.getColumnCount() - 2 <= a;) { model.addColumn(new Object[] { "partial" }); } // Create the object that holds all the columns Object[] temp = new Object[2+list.size()]; temp[0] = entry.getKey(); temp[1] = entry.getValue(); int index = 2; for (Object o : list) { Map<?, ?> m = (Map<?, ?>) o; // Get the chunck-specific count with the correct key (the name) temp[index] = m.get(temp[0]); index++; } model.addRow(temp); }
我沒有在這里執行您所做的檢查。 但是,如果您修復了這些問題,則應該能夠使其正常運行。
然后使用以下命令創建JTable
:
JTable t = new JTable(toTableModel(wordsInTheMiddle, wordsPerChunck));
多虧了Am9417,我明白了! 如果有人感興趣,這是結果:
package einlesen;
/**
* @author angeliqueschulberger
*
*/
import java.io.*;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTable;
import javax.swing.RowSorter;
import javax.swing.SortOrder;
import javax.swing.WindowConstants;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;
public class Einlesen {
/**
* @param args
* @throws IOException
*/
static List<String> word = new ArrayList<String>();
static Map<String, Integer> wordsInTheMiddle = new HashMap<>();
@SuppressWarnings({ "resource" })
public static void main(String[] args) throws IOException {
Scanner scan = new Scanner(System.in);
String antwort;
System.out.println("Welches Dokument wollen Sie? Geben Sie dabei den Path an, bitte.");
antwort = ("Downloads/lol.txt"); // scan.nextLine();
String path = System.getProperty("user.home");
// System.out.println(path);
File file = Paths.get(path, antwort).toFile();
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
Scanner sc = new Scanner(br);
//List<String> word = new ArrayList<String>();
while (sc.hasNext()) {
String wort = sc.next();
// Remove quotes
if (wort.startsWith("\"")) {
wort = wort.substring(1);
}
if (wort.endsWith("\"")) {
wort = wort.substring(0, wort.length() - 1);
}
word.add(wort);
}
br.close();
int chunkStartIndex = 0;
Map<String, Integer> wordsInTheMiddle = new HashMap<>();
List<Map<String,Integer>> wordsPerChunck = new ArrayList<>();
int chunckNumber = 0;
while (word.size() - chunkStartIndex > 0) {
int chunkEndIndex = chunkStartIndex + 2000;
if (chunkEndIndex > word.size()) {
chunkEndIndex = word.size();
}
List<String> chunkOfWords = word.subList(chunkStartIndex, chunkEndIndex);
Map<String, Integer> countInChunck = new HashMap<>();
wordsPerChunck.add(countInChunck);
for (int i = 0; i < chunkOfWords.size(); i++) {
String word1 = chunkOfWords.get(i);
if (word1.matches("[A-Z][a-z][a-z]\\w+")) {
wordsInTheMiddle.putIfAbsent(word1, 0);
int oldCount = wordsInTheMiddle.get(word1);
wordsInTheMiddle.put(word1, oldCount + 1);
countInChunck.putIfAbsent(word1, 0);
// Increase the count in this chunck
countInChunck.put(word1, countInChunck.get(word1) + 1);
}
}
// do not process the last word! Would cause an index out of bounds exception.
for (int i = 0; i < chunkOfWords.size() - 1; i++) {
String word1 = chunkOfWords.get(i);
if (word1.matches("\\w*(\\.|\\?|!)$")) {
// Word is at end of sentence
String nextWord = chunkOfWords.get(i + 1);
if (wordsInTheMiddle.getOrDefault(nextWord, 0) < 2) {
// sort out words that appear at the beginning of a sentence and appear less
// than 2 times in the text
wordsInTheMiddle.remove(nextWord);
}
}
}
// remove blacklisted words
String[] blacklist = { "This", "When", "Night", "Most", "Stone", "There", "Bonfire", "Tuesday", "Their",
"They", "Professor", "Famous", "About", "Madam", "Nearly", "Aunt", "What", "Uncle", "Mommy",
"Scars", "Scotch", "Every", "That" };
for (String listedWord : blacklist) {
wordsInTheMiddle.remove(listedWord);
}
System.out.println("Mitte: " + wordsInTheMiddle);
chunkStartIndex = chunkEndIndex;
}
JTable t = new JTable(toTableModel(wordsInTheMiddle, wordsPerChunck));
TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(t.getModel());
t.setRowSorter(sorter);
List<RowSorter.SortKey> sortKeys = new ArrayList<>(25);
sortKeys.add(new RowSorter.SortKey(1, SortOrder.DESCENDING));
sorter.setSortKeys(sortKeys);
JPanel p = new JPanel();
p.add(t);
JFrame f = new JFrame();
f.add(p);
f.setSize(700, 600);
f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
f.setVisible(true);
f.setTitle(antwort);
}
public static TableModel toTableModel(Map<?, ?> map, List<Map<String, Integer>> list) {
DefaultTableModel model = new DefaultTableModel(new Object[] { "Key", "Value" }, 0);
for (Map.Entry<?, ?> entry : map.entrySet()) {
for (int a = word.size()/2000;model.getColumnCount() - 2 <= a;)
{
model.addColumn(new Object[] { "partial" });
}
Object[] temp = new Object[2+list.size()];
temp[0] = entry.getKey();
temp[1] = entry.getValue();
int index = 2;
for (Object o : list) {
Map<?, ?> m = (Map<?, ?>) o;
// Get the chunck-specific count with the correct key (the name)
temp[index] = m.get(temp[0]);
index++;
}
model.addRow(temp);
}
return model;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.