[英]How to split a sentence into words and punctuations in java
我想將字符串類型的給定句子拆分為單詞,並且我還希望將標點符號添加到列表中。
例如,如果句子是: “薩拉的狗'咬'鄰居”。
我希望輸出為: [Sara's,dog,',bit,',the,neighbour ,.]
使用string.split(“”)可以按空格將單詞拆分成單詞,但我希望標點符號也出現在結果列表中。
String text="Sara's dog 'bit' the neighbor."
String list = text.split(" ")
the printed result is [Sara's, dog,'bit', the, neighbour.]
I don't know how to combine another regex with the above split method to separate punctuations also.
我已經嘗試過但沒有解決的一些參考資料
1. 在Java中使用標點符號和空格等通過正則表達式拆分字符串
輸入和輸出示例
String input1="Holy cow! screamed Jane."
String[] output1 = [Holy,cow,!,screamed,Jane,.]
String input2="Select your 'pizza' topping {pepper and tomato} follow me."
String[] output2 = [Select,your,',pizza,',topping,{,pepper,and,tomato,},follow,me,.]
與其嘗試提出一種模式,不如通過提出一種要捕獲的元素的模式來解決該挑戰。
盡管它比簡單的split()
更多的代碼,但仍可以在Java 9+中的單個語句中完成:
String regex = "[\\p{L}\\p{M}\\p{N}]+(?:\\p{P}[\\p{L}\\p{M}\\p{N}]+)*|[\\p{P}\\p{S}]";
String[] parts = Pattern.compile(regex).matcher(s).results().map(MatchResult::group).toArray(String[]::new);
在Java 8或更早版本中,您可以這樣編寫:
List<String> parts = new ArrayList<>();
Matcher m = Pattern.compile(regex).matcher(s);
while (m.find()) {
parts.add(m.group());
}
說明
\\p{L}
是Unicode 字母 , \\\\p{N}
是Unicode 數字 ,而\\\\p{M}
是Unicode 標記 (例如重音符號)。 結合起來,它們在這里被視為“單詞”中的字符。
\\p{P}
是Unicode 標點符號 。 “單詞”可以在單詞內部嵌入單個標點符號。 之前的模式|
在給定定義的情況下,匹配一個“單詞”。
\\p{S}
是Unicode 符號 。 未嵌入在“單詞”中的標點符號和符號分別進行匹配。 那是|
之后的模式|
。
這樣就不會發現Unicode類別Z
( 分隔符 )和C
( 其他 )類別,這意味着將跳過任何此類字符。
測試
public class Test {
public static void main(String[] args) {
test("Sara's dog 'bit' the neighbor.");
test("Holy cow! screamed Jane.");
test("Select your 'pizza' topping {pepper and tomato} follow me.");
}
private static void test(String s) {
String regex = "[\\p{L}\\p{M}\\p{N}]+(?:\\p{P}[\\p{L}\\p{M}\\p{N}]+)*|[\\p{P}\\p{S}]";
String[] parts = Pattern.compile(regex).matcher(s).results().map(MatchResult::group).toArray(String[]::new);
System.out.println(Arrays.toString(parts));
}
}
輸出量
[Sara's, dog, ', bit, ', the, neighbor, .]
[Holy, cow, !, screamed, Jane, .]
[Select, your, ', pizza, ', topping, {, pepper, and, tomato, }, follow, me, .]
Arrays.stream( s.split("((?<=[\\s\\p{Punct}])|(?=[\\s\\p{Punct}]))") )
.filter(ss -> !ss.trim().isEmpty())
.collect(Collectors.toList())
參考:
ArrayList<String> chars = new ArrayList<String>();
String str = "Hello my name is bob";
String tempStr = "";
for(String cha : str.toCharArray()){
if(cha.equals(" ")){
chars.add(tempStr);
tempStr = "";
}
//INPUT WHATEVER YOU WANT FOR PUNCTATION WISE
else if(cha.equals("!") || cha.equals(".")){
chars.add(cha);
}
else{
tempStr = tempStr + cha;
}
}
chars.add(str.substring(str.lastIndexOf(" "));
那? 假定句子中每個單詞都有空格,則應添加每個單詞。 對於!和。,您也必須對此進行檢查。 非常簡單。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.