【问题标题】:Java String parsing and summingJava字符串解析和求和
【发布时间】:2013-03-17 17:10:34
【问题描述】:

我正在寻找解析输入 String,并且在执行此操作时,我想检查每个单词的出现次数,同时删除所有非字母字符。

例如:

String str = "test man `xy KA XY test!.. KA kA TeST man poqw``e TES`T"
String s = line.replaceAll("[^\\p{L}\\p{N}\\ ]", "");
String[] werd = alphaLine.split(" ");

for(int i=0; i<werd.size(); i++) {
     if(werd[i].toLowerCase().equals("test")) {
         testcounter++;
     elseif(werd[i].toLowerCase().equals("ka")) {
         kacounter++;
     etc..

我将检查很长时间 Strings,并将检查许多目标 Strings(在此示例中为 katest),并试图查看我是否可以在一次通过,现在看来,对于.replaceAll().split(),然后是 for 循环,我将遍历所有 Strings 3 次,而它可以完成一次。

【问题讨论】:

  • 我不会害怕三个循环。不过,请查看StreamTokenizers。
  • 有很好的数据结构,经过良好测试的实现,例如:code.google.com/p/patricia-trie

标签: java string parsing


【解决方案1】:

不确定我是否在同一页面上,但听起来您在问如何在搜索单词时减少查找次数。如果您有大量搜索词,这可能不是最好的方法,但应该为较小的列表提供每个词的出现次数。

Map<String, Integer> occurrences = new HashMap<String, Integer>();
List<String> words = new ArrayList<String>();
words.add("foo");
words.add("bar");

//build regex - note: if this is done within an outer loop, then you should consider using StringBuilder instead
//The \b in regex is a word boundary
String regex = "\\b(";
for(int i = 0; i < words.size(); i++) {
    //add word to regex
    regex += (0 == i ? "" : "|") + words.get(i);

    //initial occurrences
    occurrences.add(words.get(i), 0);
}
regex += ")\\b";
Pattern patt = Pattern.compile(regex);
Matcher matcher = patt.matcher(search_string);

//check for matches
while (matcher.find()) {
    String key = matcher.group();
    int numOccurs = occurrences.get(key) + 1;
    occurrences.put(key, numOccurs);
}

编辑:这是假设您在此之前处理了非字母要求

【讨论】:

    猜你喜欢
    • 2014-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多