簡體   English   中英

JAVA按字,標點和引號分隔句子

[英]JAVA split sentence by words, punctuation and quotes

我正在嘗試使用正則表達式拆分句子。

句子:

"Hallo, I'm a dog. The end. Someone said: \"Earth is Earth\". Is it good? I like it! 'He is right' said I."

當前正則表達式:

\\s+|(?<=[\\p{Punct}&&[^']])|(?=[\\p{Punct}&&[^']])

當前結果:

{"Hallo", ",", "I'm", "a", "dog", ".", "The", "end", ".", "Someone",
"said", ":", **""**, """ , "Earth", "is", "Earth", """, ".", "Is", "it",
"good", "?", "I", "like", "it", "!", **"'He"**, "is", **"right'"**,
"said", "I", "."}

我在第一個引號前加上了多余的"" ,並且它不會將'與單詞分開。

我想要的結果:

{"Hallo", ",", "I'm", "a", "dog", ".", "The", "end", ".", "Someone",
"said", ":", """ , "Earth", "is", "Earth", """, ".", "Is", "it",
"good", "?", "I", "like", "it", "!", "'" , "He", "is", "right", "'",
"said", "I", "."}

編輯:對不起! 然后提供更多代碼:

String toTest =  "Hallo, I'm a dog. The end. Someone said: \"Earth is Earth\". Is it good? I like it! 'He is right' said I.";
String [] words = toTest.split("\\s+|(?<=[\\p{Punct}&&[^']])|(?=[\\p{Punct}&&[^']])");

並產生單詞列表:

單詞= {“ Hallo”,“,”,“我”,“ a”,“ dog”,“。”,“ The”,“ end”,“。”,“ Someone”,“ said”,“ :“, ”“ ,”“,”地球“,”是“,”地球“,”“”,“。”,“是”,“它”,“好”,“?”,“我”, “ like”,“ it”,“!”, “'He” ,“ is”, “ right'” ,“ said”,“ I”,“。”}

您可以嘗試:

\\s+|(?<=[\\p{Punct}&&[^']])(?!\\s)|(?=[\\p{Punct}&&[^']])(?<!\\s)|(?<=[\\s\\p{Punct}]['])(?!\\s)|(?=['][\\s\\p{Punct}])(?<!\\s)

said: \\"Earth的問題是said: \\"Earth是您在空格之前和之后分裂,所以我在標點符號周圍分裂的部分添加了負面的前瞻性和負面的前瞻性。

我還添加了兩種情況,用於在單引號前后加上空格或標點符號的情況下對單引號進行拆分。

但是,正如@RealSkeptic在他的評論中寫道,這將無法解決

像海豚鼻子一樣表示占有的單引號

您可能需要為此編寫一個真正的解析器。

您可以嘗試將特殊字符與單詞分開:

yoursentence.replaceAll("([^\\w ])", " $1 ").split(" +");

這弄亂了空格,但是我想您不需要關心句子中彼此相鄰的數目。 此外,“位”比您的:D更簡單

可復制的代碼嘗試:

public static void main(String[] args) {
    String s = "Hallo, I'm a dog. The end. Someone said: \"Earth is Earth\". Is it good? I like it! 'He is right' said I.";
    String replaceAll = s.replaceAll("([^\\w ])", " $1 ");
    List<String> asList = Arrays.asList(replaceAll.split(" +"));

    for (String string : asList) {
        System.out.println(string);
    }
}

盡管用一個正則表達式可以解決問題,但我的方法是將工作分為幾個步驟,每個步驟都做一件事情。

所以我建議您創建一個接口:

public interface IProcess {
    List<String> process (List<String> input);
}

現在,您可以從一個列表開始,該列表包含整個句子作為第一個元素,並返回按空格分隔的單詞:

    return Arrays.asList (input.get (0).split ("\\s+") );

下一步是為每種特殊字符編寫處理器並將它們鏈接起來。 例如,您可以剝離.,!? 在每個單詞的末尾清除輸入內容,以進行下一步。

這樣,只要發現錯誤,就可以輕松地為每個處理器編寫單元測試,並輕松縮小需要改進的部分。

暫無
暫無

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

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