public class HashMapsTest {
static Scanner sc = new Scanner(System.in);
public static void main(String[] args) throws FileNotFoundException {
sc = new Scanner(new FileInputStream("TextFile")); // read a file
ArrayList<ArrayList<String>> words = new ArrayList<ArrayList<String>>(); // list to put the words inside
StringBuffer sb = new StringBuffer(); // string buffer to read the file
String[] protasi = null;
while (sc.hasNextLine()) {
sb.append(sc.nextLine() + " ");
}
protasi = sb.toString()
.split("!| !|! | ! |\\? | \\?| \\? |\\?|\\.|\\. | \\.| \\."); // split the string into sentences
String[][] leksis = new String[protasi.length][];
for (int i = 0; i < protasi.length; i++) {
leksis[i] = protasi[i].split(" , |,| ,| ,| - |-| -|- | -- |--| --|-- | : |:| :|: | ; |;| ;|; | | | ' |'|"
+ " '|' | \" |\"| \" | \"| ` |`| `|` "); // split the sentences into words
}
// take the table with the words and put it into a list
for (int i = 0; i < protasi.length; i++) {
String x = "";
ArrayList<String> line = new ArrayList<String>();
for (int j = 0; j < leksis[i].length; j++) {
x = leksis[i][j];
if (x.length() != 0) {
line.add(x);
}
}
if (line.size() != 0) {
words.add(line);
}
}
HashMap<String, HashMap<String, Integer>> outhm = new HashMap<String, HashMap<String, Integer>>();
HashMap<String, Integer> inhm = new HashMap<String, Integer>();
for (int i = 0; i < words.size(); i++) {
for (int j = 0; j < words.get(i).size(); j++) {
if (!inhm.containsKey(words.get(i).get(j))) {
inhm.put(words.get(i).get(j), 1);
} else {
inhm.put(words.get(i).get(j), inhm.get(words.get(i).get(j)) + 1);
}
if (!outhm.containsKey(words.get(i).get(j))) {
outhm.put(words.get(i).get(j), inhm);
} else {
outhm.put(words.get(i).get(j), inhm);
}
}
}
System.out.println(outhm.toString());
}
}
我想创建一个返回此输出的hashmap:
{'man':{'我':3,'是':3,'a':2,'生病':1,'恶意':1,'an':1, '没有吸引力':1},'肝':{'我':1,'相信':1,'我':1,'是':1, '患病':1},...}
而不是那个输出我得到:
{ails = {ails = 1,about = 1,for = 1,I = 5,sick = 1,believe = 1,do = 1,not = 1, 和= 1,me = 1,unattractive = 1,man = 3,spiteful = 1,all = 1,a = 2,疾病= 1, 肝脏= 1,没有= 1,但是= 1,是= 1,am = 3,我= 2,an = 1,at = 1,what = 1, 病态= 1,知道= 2,某些= 1},约= {ails = 1,约= 1,= 1,I = 5, 病= 1,相信= 1,做= 1,不= 1,= 1,我= 1,不吸引人= 1,男人= 3, spiteful = 1,all = 1,a = 2,疾病= 1,肝脏= 1,没有= 1,但是= 1, is = 1,am = 3,my = 2,an = 1,at = 1,what = 1,sickased = 1,know = 2, 某些= 1} ...}