[英]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.