[英]My word count program is not working
下面的代码用于计算列表y中的单词通过FileReader
或列表x在文档中出现的次数。 最终,我也希望列表y也成为导入的文档,但是当我在文档上运行代码时,它要么给我一个错误的计数,要么根本不给我计数。 这是怎么回事?
这些文件也是表单记事本。 我正在使用Windows
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class test {
@SuppressWarnings("resource")
public static void main(String[] args) throws Exception {
don w = new don();
List<Integer> ist = new ArrayList<Integer>();
// List<String> x =Arrays.asList
// ("is","dishonorable","dismal","miserable","horrible","discouraging","distress","anguish","mine","is");
BufferedReader in = new BufferedReader(new FileReader("this one.txt"));
String str;
List<String> list = new ArrayList<String>();
while ((str = in.readLine()) != null) {
list.add(str);
// System.out.println(list);
List<String> y = Arrays.asList("Hello", "the", "string", "is", "mine");
for (String aY : y) {
int count = 0;
for (String aX : list) {
if (aY.contains(aX)) {
count++;
}
}
ist.add(count);
// no need to reset the count
}
int g = ist .stream()
.mapToInt(value -> value)
.sum();
System.out.println(g);
}
}
}
如果您想数数,您应该...数数。
在这里,您仅检查字符串是否包含子字符串。
相反,您应该大致执行以下操作:
static int count(String line, String word) {
int count = 0;
for (int offset = line.indexOf(word); offset >= 0; offset = line.indexOf(word, offset + 1 + word.length())) {
count++;
}
return count;
}
现在,当然,您可能必须考虑到要查找子字符串而不是单词的事实。 但是,如果您已经了解了这一点,则可能需要使用正则表达式来进一步帮助您。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.