簡體   English   中英

計算java字符串中的句子數

[英]Count number of sentence in a java string

嗨,我想計算一個字符串中的句子數,到目前為止我正在使用這個:

int count = str.split("[!?.:]+").length;

但我的字符串包含“。” 例如在名字和單詞之間

“他的名字是 Walton DC,他去年剛剛完成了他的 B.Tech。”

現在使用上面的行作為示例 count 將返回 4 個句子,但只有一個。

那么如何應對這些情況呢?

您可以使用BreakIterator ,並檢測不同類型的文本邊界

在你的情況下句子:

private static void markBoundaries(String target, BreakIterator iterator) {
    StringBuffer markers = new StringBuffer();
    markers.setLength(target.length() + 1);
    for (int k = 0; k < markers.length(); k++) {
        markers.setCharAt(k, ' ');
    }
    int count = 0;
    iterator.setText(target);
    int boundary = iterator.first();
    while (boundary != BreakIterator.DONE) {
        markers.setCharAt(boundary, '^');
        ++count;
        boundary = iterator.next();
    }
    System.out.println(target);
    System.out.println(markers);
    System.out.println("Number of Boundaries: " + count);
    System.out.println("Number of Sentences: " + (count-1));
}

public static void main(String[] args) {
    Locale currentLocale = new Locale("en", "US");
    BreakIterator sentenceIterator
            = BreakIterator.getSentenceInstance(currentLocale);
    String someText = "He name is Walton D.C. and he just completed his B.Tech last year.";
    markBoundaries(someText, sentenceIterator);
    someText = "This order was placed for QT3000! MK?";
    markBoundaries(someText, sentenceIterator);

}

輸出將是:

He name is Walton D.C. and he just completed his B.Tech last year.
^                                                                 ^
Number of Boundaries: 2
Number of Sentences: 1
This order was placed for QT3000! MK?
^                                 ^  ^
Number of Boundaries: 3
Number of Sentences: 2

解決方案可能是在點的情況下,您可以檢查后面是否有空格和大寫字母。

“[點][空格][大寫字母]”

這將是對判決的肯定

更新相同的代碼:

public static void main( String args[] ) {
      // String to be scanned to find the pattern.
      String line = "This order was placed for QT3000! MK? \n Thats amazing. \n But I am not sure.";
  String pattern = "([.!?])([\\s\\n])([A-Z]*)";

  // Create a Pattern object
  Pattern r = Pattern.compile(pattern);

  // Now create matcher object.
  Matcher m = r.matcher(line);
  int count=0;
  while (m.find( )) {
      count++;
  }
  count++; //for the last line, which will not get included here.
  System.out.println("COUNT=="+count);
}

如果前面有一個或多個大寫字母,則一種解決方案是跳過點。 在這種情況下,名稱(如果它們是大寫的)。 實現這一點,你將只有一個句子。

另一種解決方案:改進這里的一個答案可能是:[小寫]([點]或[?]或[!])[空格][大寫]

但是就像我說的,如果沒有確切的規則,那幾乎是不可能的。

簡單的方法

公共類計數線{

public static void main(String[] args) {
    // TODO Auto-generated method stub
    String s="Find the number Sentence";
    int count=0;
    for (int i = 0; i < s.length(); i++) {
        if(s.charAt(i)==' ') {
            count++;
        }
    }
    count=count+1;
    System.out.println(count);
}

}

暫無
暫無

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

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