簡體   English   中英

抓取字符串中的單詞和字符數

[英]Grab word and character counts in string

我正在嘗試編寫一種高效的方法,該方法在兩種“模式”( WORDCHARACTER )下運行,該模式接受一個String並告訴我其中的單詞(以1+個空格分隔)或字符(非空白字符)數量它:

public int getCount(String toExamine, boolean wordMode) {
    int count = 0;

    if(wordMode) {
        // Return the number of words.
    }
    else {
        // Return the number of characers.
    }

    return count;
}

知道我可以使用StringTokenizer完成WORD模式版本:

StringTokenizer tokenizer = new StringTokenizer(" ");

但是我對於使用CHARACTER模式(非空白字符的數量)絕對不了解。 我確定我可以使用像這樣的粗略的東西:

for(int i = 0; i < toExamine.length; i++)
    if(Character.isSpace(toExamine.charAt(i)))
        count++;

但這有點丑陋,可能不是最有效的方式(與StringTokenizer相同)。 可以在這里使用正則表達式,還是其他一些Java String / Character瘋狂功能,以超級高效的方式為我提供所需的東西? 我正在這里處理數千萬個String。 提前致謝。

隱藏到char數組,並使用for循環進行迭代

int charCount =0;
for(int i=0; i<sentence.length(); i++) {
    if(!Character.isWhitespace(sentence.charAt(i))) {
        charCount++;
    }
}

以其他方式替換所有空格並使用以下代碼計算長度

int charcount = 0;
String newSentence =sentence.replaceAll("\\s+", "");
charcount = newSentence.length();

這不是for循環要快,但是如果需要使用正則表達式,可以嘗試如下操作:

int noSpaces=toExamine.split("\\s+").length-1; 

pf字符數為:

int noChar=toExamine.length-noSpaces;

下面的測試程序產生以下結果。 該程序將輸出5組這樣的結果,但是我在這里只顯示一個。 //的行是我的注釋,而不是程序的輸出。

// Percentage of non-space over space is approximately 0.857
// Length of the full string generated is 1 075 662
0.857 1075662
// Name_of_method (Result): 15_Runs_In_Microseconds | Average_In_Microseconds
countWords_1 (131489): 20465 20240 21045 20193 20000 19972 20551 39489 19859 19971 19889 19877 20049 19900 19949 | 21429
countWords_2 (131489): 255500 258723 254543 255956 253606 263549 254096 254402 254191 254296 253752 261501 260788 261574 254178 | 256710
countWords_3 (131489): 26225 25022 24830 24829 24545 24819 25459 24625 25628 24700 24936 24794 24794 24849 25026 | 25005
countWords_4 (131489): 24537 24169 25283 24862 23863 23902 24068 23906 51472 23731 23889 23844 23832 24275 23896 | 25968
countWords_5 (131489): 81087 112095 80008 81290 81472 80581 80717 80460 79870 80557 80694 80923 145686 80564 80849 | 87123
countWords_6 (131489): 114391 114146 111946 111873 112331 167207 134117 118217 112843 112804 113533 111834 112830 112392 118181 | 118576
countChars_1 (922546): 150507 109102 150453 111352 149753 108099 153842 109034 150817 117258 149219 108194 152839 110340 149524 | 132022
countChars_2 (922546): 28779 29473 52499 27182 26519 27743 26717 27161 26451 27060 26307 27309 26350 62824 33134 | 31700
countChars_3 (922546): 25408 25127 24980 24832 24624 24671 24848 24712 24634 24622 24607 24613 24661 24765 24883 | 24799
countChars_4 (922546): 81489 82246 80906 80718 80803 81147 81113 81798 81030 81024 108508 80768 80780 80671 80753 | 82916
countChars_5 (922546): 26086 25546 24846 43734 25016 25083 24894 25530 25031 25041 25114 24935 25358 24895 43498 | 27640
countChars_6 (922546): 102559 102257 101381 101589 103432 101739 102794 129472 101305 101834 103124 101486 101254 102874 101481 | 103905

countWords_2countWords_6是涉及regex和replaceAll技巧的一線方法,與其他方法相比非常慢。 countWords_5使用預編譯的Pattern進行匹配,比使用replaceAll的單行代碼更快,但與其他代碼相比仍然較慢。

countWords_3countWords_4是簡單的循環,但是有一些細微的差別。 時間上並沒有確定的差異。 (我希望時序更大或更小保持一致,時序差異至少應在5毫秒左右)。

countWords_1使用帶有默認定界符的 StringTokenizer ,該定界符不包含Unicode字符 因此,由於語義完全不同,因此此處無法進行很好的比較。

對於計算單詞數(定義為非空白字符序列),簡單循環比我能想到的regex方法要快。

countChars_1countChars_6是涉及regex和replaceAll技巧的一線解決方案。 同樣,它比使用預編譯的Pattern countChars_4慢。 同樣,所有正則表達式解決方案都比簡單循環慢。

countChars_2countChars_3countChars_5是簡單循環的一些變體。 我觀察到的許多運行countChars_3countChars_5的差異不是非常一致,因此不是結論性的。 但是countChars2通常會稍慢一些,可能是由於必須將新內存分配給toCharArray函數返回的char[]

我不保證這里使用的方法是最快的,但是它顯示了一些關於簡單循環與正則表達式解決方案相比的想法。


您可以運行此測試程序並自行決定。 我已經編寫了測試,以便您可以自由地:

  • 更改生成的測試字符串的長度以及出現的空格字符的頻率。

    當前,測試字符串的長度在70萬至1300萬個字符之間是隨機的,並且非空對空字符的比率在4:1至9:1之間變化(我猜一般的文本)。 您可以將FLUCTUATION設置為0,以便長度或比率是固定的-當您要測試邊緣情況時非常有用。

  • 替換測試字符串的生成方式(真實數據而不是隨機生成的字符串)。

    當前,使用了ASCII字符的子集:大約64個非空格字符; 空格,換行符,制表符和回車符用作空白字符。 有Unicode空格字符,但當前測試中未包括。

  • 添加新方法進行測試,並標有@Test批注。

import java.util.regex.Pattern;
import java.util.regex.Matcher;

import java.util.Arrays;
import java.util.ArrayList;
import java.util.Random;
import java.util.StringTokenizer;

import java.lang.reflect.Method;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.annotation.ElementType;

class TestStringProcessing_15028652 {

  @Retention(RetentionPolicy.RUNTIME)
  @Target(ElementType.METHOD)
  private @interface Test {};

  // From 0.80 - 0.90 (4:1 to 9:1 non-space:space characters ratio)
  private static final double NON_SPACE_RATIO = 0.85;
  private static final double NON_SPACE_RATIO_FLUCTUATION = 0.05;

  // With the way the test is written, it is not going to work well with small input (1000 is NOT enough)
  // Currently set to 700 000 - 1 300 000 characters
  private static final int NUM_CHARS = 1000000;
  private static final int NUM_CHARS_FLUCTUATION = 300000;

  // Some whitespace characters
  private static final char WHITESPACES[] = {' ', '\t', '\r', '\n'};

  // Number of times to run all methods
  private static final int NUM_OUTER = 5;
  // Number of times to run each method
  private static final int NUM_REPEAT = 15;

  static {
    for (int i = 0; i < WHITESPACES.length; i++) {
      assert(Character.isWhitespace(WHITESPACES[i]));
    }
  }

  private static Random random = new Random();

  private static String generateInput() {

    double nonSpaceRatio = NON_SPACE_RATIO + random.nextDouble() * 2 * NON_SPACE_RATIO_FLUCTUATION - NON_SPACE_RATIO_FLUCTUATION;
    int numChars = NUM_CHARS + random.nextInt(2 * NUM_CHARS_FLUCTUATION) - NUM_CHARS_FLUCTUATION;

    System.out.printf("%.3f %d\n", nonSpaceRatio, numChars);

    StringBuffer output = new StringBuffer();

    for (int i = 0; i < numChars; i++) {
      if (random.nextDouble() < nonSpaceRatio) {
        output.append((char) (random.nextInt(64) + '0'));
      } else {
        output.append(WHITESPACES[random.nextInt(WHITESPACES.length)]);
      }
    }

    return output.toString();
  }

  private static ArrayList<Method> getTestMethods() {
    Class<?> klass = null;
    try {
      klass = Class.forName(Thread.currentThread().getStackTrace()[1].getClassName());
    } catch (Exception e) {
      e.printStackTrace();
      System.err.println("Something really bad happened. Bailling out...");
      System.exit(1);
    }
    Method[] methods = klass.getMethods();
    // System.out.println(klass);
    // System.out.println(Arrays.toString(methods));

    ArrayList<Method> testMethods = new ArrayList<Method>();

    for (Method method: methods) {
        if (method.isAnnotationPresent(Test.class)) {
          testMethods.add(method);
        }
    }

    return testMethods;
  }


  public static void runTestReflection() {
    ArrayList<Method> methods = getTestMethods();

    for (int t = 0; t < NUM_OUTER; t++) {
      String input = generateInput();

      for (Method method: methods) {

        try {
          System.out.print(method.getName() + " (" + method.invoke(null, input) + "): ");
        } catch (Exception e) {
          e.printStackTrace();
        }

        long sum = 0;
        for (int i = 0; i < NUM_REPEAT; i++) {
          long start, end;
          Object result;

          try {
            start = System.nanoTime();
            result = method.invoke(null, input);
            end = System.nanoTime();

            System.out.print((end - start) / 1000 + " ");
            sum += (end - start) / 1000;
          } catch (Exception e) {
            e.printStackTrace();
          }
        }

        System.out.println("| " + sum / NUM_REPEAT);
      }

      System.out.println();
    }
  }

  public static void main(String args[]) {
    runTestReflection();
  }

  @Test
  public static int countWords_1(String input) {
    // WARNING: This is NOT the same as isWhitespace, since isWhitespace
    // also consider Unicode characters.
    return new StringTokenizer(input).countTokens();
  }

  @Test
  public static int countWords_2(String input) {
    return input.replaceAll("\\S+", "$0 ").length() - input.length();
  }

  @Test
  public static int countWords_3(String input) {
    int count = 0;
    boolean in = false;

    for (int i = 0; i < input.length(); i++) {
      if (!Character.isWhitespace(input.charAt(i))) {
        if (!in) {
          in = true;
          count++;
        }
      } else {
        in = false;
      }
    }

    return count;
  }

  @Test
  public static int countWords_4(String input) {
    int count = 0;

    for (int i = 0; i < input.length(); i++) {
      if (!Character.isWhitespace(input.charAt(i))) {
        do {
          i++;
        } while (i < input.length() && !Character.isWhitespace(input.charAt(i)));
        count++;
      }
    }

    return count;
  }

  @Test
  public static int countWords_5(String input) {
    int count = 0;
    Matcher m = p.matcher(input);

    while (m.find()) {
      count++;
    }

    return count;
  }

  @Test
  public static int countWords_6(String input) {
    return input.replaceAll("\\s*+\\S++\\s*+", " ").length();
  }

  @Test
  public static int countChars_1(String input) {
    return input.replaceAll("\\s+", "").length();
  }

  @Test
  public static int countChars_2(String input) {
    int count = 0;
    for (char c: input.toCharArray()) {
      if (!Character.isWhitespace(c)) {
        count++;
      }
    }

    return count;
  }

  @Test
  public static int countChars_3(String input) {
    int count = 0;
    for (int i = 0; i < input.length(); i++) {
      if (!Character.isWhitespace(input.charAt(i))) {
        count++;
      }
    }

    return count;
  }

  private static Pattern p = Pattern.compile("\\S+");

  @Test
  public static int countChars_4(String input) {
    Matcher m = p.matcher(input);
    int count = 0;

    while (m.find()) {
      count += m.end() - m.start();
    }

    return count;
  }

  @Test
  public static int countChars_5(String input) {
    int count = input.length();
    for (int i = 0; i < input.length(); i++) {
      if (Character.isWhitespace(input.charAt(i))) {
        count--;
      }
    }

    return count;
  }

  @Test
  public static int countChars_6(String input) {
    return input.length() - input.replaceAll("\\S+", "").length();
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM