【发布时间】:2020-02-22 23:46:51
【问题描述】:
我正在处理一项需要将段落拆分为句子的任务。例如给定一个段落:
"This is a long string with some numbers 123.456,78 or 100.000 and e.g. some abbreviations in it, which shouldn't split the sentence. Sometimes there are problems, i.e. in this one. here and abbr at the end x.y.. cool."
我需要以下 4 句话:
This is a long string with some numbers 123.456,78 or 100.000 and e.g. some abbreviations in it, which shouldn't split the sentence.
Sometimes there are problems, i.e. in this one.
here and abbr at the end x.y..
cool
现在它与用 JavaScript 实现的this task 非常相似。
var re = /\b(\w\.\w\.)|([.?!])\s+(?=[A-Za-z])/g;
var str = 'This is a long string with some numbers 123.456,78 or 100.000 and e.g. some abbreviations in it, which shouldn\'t split the sentence. Sometimes there are problems, i.e. in this one. here and abbr at the end x.y.. cool.';
var result = str.replace(re, function(m, g1, g2){
return g1 ? g1 : g2+"\r";
});
var arr = result.split("\r");
document.body.innerHTML = "<pre>" + JSON.stringify(arr, 0, 4) + "</pre>";
我试图在this link 的帮助下在 Java 中实现这一点,但在我的 Java 代码中如何使用上面的 snipper 中的 replace 函数时遇到了困难。
public static void main(String[] args) {
String content = "This is a long string with some numbers 123.456,78 or 100.000 and e.g. some abbreviations in it, which shouldn't split the sentence. Sometimes there are problems, i.e. in this one. here and abbr at the end x.y.. cool.";
Pattern p = Pattern.compile("/\\b(\\w\\.\\w\\.)|([.?!])\\s+(?=[A-Za-z])/g");
Matcher m = p.matcher(content);
List<String> tokens = new LinkedList<String>();
while (m.find()) {
String token = m.group(1); // group 0 is always the entire match
tokens.add(token);
}
System.out.println(tokens);
}
如何在 Java 编程中做同样的事情?对于这个给定的示例文本,有没有比这更好的方法来将段落拆分为 Java 中的句子?
【问题讨论】:
-
第三句通常会被认为是不恰当的英语,因为我们不会在句末写两个句号。
-
并且它不包含动词。第 4 句也没有。
-
@user207421,我正在尝试将工作的 Javascript 代码转换为 Java,但我无法理解如何去做。
标签: javascript java regex