2017-06-12 60 views
3

我使用BreakIterator.getWordInstance將中文文本拆分爲單詞。這是我的例子BreakIterator與中文文本無法正常工作

import java.text.BreakIterator; 
import java.util.Locale; 

public class Sample { 
    public static void main(String[] args) { 
     String stringToExamine = "I like to eat apples. 我喜歡吃蘋果。"; 

     //print each word in order 
     BreakIterator boundary = BreakIterator.getWordInstance(new Locale("zh", "CN")); 
     boundary.setText(stringToExamine); 

     printEachForward(boundary, stringToExamine); 
    } 

    public static void printEachForward(BreakIterator boundary, String source) { 
     int start = boundary.first(); 
     for (int end = boundary.next(); end != BreakIterator.DONE; start = end, end = boundary.next()) { 
      System.out.println(start + ": " + source.substring(start, end)); 
     } 
    } 
} 

我的示例文本從https://stackoverflow.com/a/42219474/954439

,我得到的是

0: I 
1: 
2: like 
6: 
7: to 
9: 
10: eat 
13: 
14: apples 
20: . 
21: 
22: 我喜歡吃蘋果 
28: 。 

,而輸出拍攝,預計產量

0 I 
1 
2 like 
6 
7 to 
9 
10 eat 
13 
14 apples 
20 . 
21 
22 我 
23 喜歡 
25 吃 
26 蘋果 
28 。 

我甚至嘗試純粹的中文文本,但這些單詞在空格和標點符號上被打破acters。

我是一個服務器編程,所以jar文件的大小不是一個大問題。我試圖找到給定內容中與使用最少公共子序列(但是在單詞上)的示例內容相比不同的單詞數量。

我在做什麼錯?

+0

@Suragch我是一個服務器編程,所以jar文件的大小不是一個大問題。我試圖找到給定內容中與使用最少公共子序列(但是在單詞上)的示例內容相比不同的單詞數量。 – srgsanky

回答

3

標準BreakIterator不支持在CJK表意字符串的不間斷字符串中檢測「字」邊界。在這個問題上有一個bug report,但它在2006年被關閉爲「不會修復」。

相反,您需要使用ICU implementation。如果您在Android上開發,則已將其作爲android.icu.text.BreakIterator。否則,您需要從http://site.icu-project.org/download下載ICU4J庫,該庫的編號爲com.ibm.icu.text.BreakIterator

+1

我想知道如何爲回答https://stackoverflow.com/a/42219474/954439的人員工作。我還看到其他宣稱BreakIterator使用中文文本的網站。 – srgsanky

+0

@srgsanky看起來答案的代碼在Android中運行,它有一個不同的BreakIterator實現。 – VGR

+0

更新了我的回答,有一個替代實現可以工作。 –