【发布时间】:2018-02-05 23:21:55
【问题描述】:
我希望能够计算每个单词在给定文件中重复的次数。但是,我在这样做时遇到了麻烦。我尝试了两种不同的方法。我使用 HashMap 并将单词作为键并将其频率作为关联值的一种。但是,这似乎不起作用,因为有了 HashMap,您无法访问指定索引处的元素。现在我尝试使用两个单独的数组列表,一个用于单词,一个用于该单词的每次出现。我的想法是这样的:在将单词添加到 wordsCount 数组列表时,如果单词已经在 wordsCount 中,则在已看到单词的索引处增加 cnt ArrayList 中元素的值。但是,我不确定要写什么来增加值
import java.io.*;
import java.lang.reflect.Array;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;
public class MP0 {
Random generator;
String delimiters = " \t,;.?!-:@[](){}_*/";
String[] stopWordsArray = {"i", "me", "my", "myself", "we", "our", "ours", "ourselves", "you", "your", "yours",
"yourself", "yourselves", "he", "him", "his", "himself", "she", "her", "hers", "herself", "it", "its",
"itself", "they", "them", "their", "theirs", "themselves", "what", "which", "who", "whom", "this", "that",
"these", "those", "am", "is", "are", "was", "were", "be", "been", "being", "have", "has", "had", "having",
"do", "does", "did", "doing", "a", "an", "the", "and", "but", "if", "or", "because", "as", "until", "while",
"of", "at", "by", "for", "with", "about", "against", "between", "into", "through", "during", "before",
"after", "above", "below", "to", "from", "up", "down", "in", "out", "on", "off", "over", "under", "again",
"further", "then", "once", "here", "there", "when", "where", "why", "how", "all", "any", "both", "each",
"few", "more", "most", "other", "some", "such", "no", "nor", "not", "only", "own", "same", "so", "than",
"too", "very", "s", "t", "can", "will", "just", "don", "should", "now"};
private static String str;
private static File file;
private static Scanner s;
public MP0() {
}
public void process() throws Exception{
ArrayList<Integer> cnt = new ArrayList<Integer>();
boolean isStopWord = false;
StringTokenizer st = new StringTokenizer(s.nextLine(), delimiters);
ArrayList<String> wordsCount = new ArrayList<String>();
while(st.hasMoreTokens()) {
String s = st.nextToken().toLowerCase();
if(!wordsCount.contains(s)) {
for(int i = 0; i < stopWordsArray.length; i++) {
isStopWord = false;
if(s.equals(stopWordsArray[i])) {
isStopWord = true;
break;
}
}
if(isStopWord == false) {
wordsCount.add(s);
cnt.add(1);
}
}
else { // i tried this but only displayed "1" for all words
cnt.set(wordsCount.indexOf(s), cnt.get(wordsCount.indexOf(s) + 1));
}
}
for(int i = 0; i < wordsCount.size(); i++) {
System.out.println(wordsCount.get(i) + " " + cnt.get(i));
}
}
public static void main(String args[]) throws Exception {
try {
file = new File("input.txt");
s = new Scanner(file);
str = s.nextLine();
String[] topItems;
MP0 mp = new MP0();
while(s.hasNext()) {
mp.process();
str = s.nextLine();
}
}
catch(FileNotFoundException e) {
System.out.println("File not found");
}
}
}
【问题讨论】:
-
如果您将键更改为单词,则哈希图的想法将起作用。我会打一个例子。
-
这听起来像是 XY 问题。您可能需要考虑这个关于计算字符串中单词频率的问题:stackoverflow.com/questions/21771566/…
标签: java string arraylist hashmap