如何在jQuery中将段落分解为句子

5
我想在jQuery中将段落拆分为句子。假设我有一个段落。
This is a wordpress plugin. its older version was 2.3.4 and new version is 2.4. But the version 2.4 had a lot of bungs. Can we solve it?

我想把它分成几个部分。
This is a wordpress plugin.
its older version was 2.3.4 and new version is 2.4.
But the version 2.4 had a lot of bungs.
Can we solve it?

有没有解决办法呢? 我尝试使用这个函数,但是当数字出现时它也会分开句子。
var result = str.match( /[^\.!\?]+[\.!\?]+/g );

谢谢


这并不简单。你可能需要使用一个库。 - Madhawa Priyashantha
2
nlp_compromise示例 - gcampbell
NLP是一个庞大的任务,因此需要一个庞大的库。 - gcampbell
@meagar 那个解决方案也破坏了像2.2.4这样的数字,谢谢。 - Ahmad
1个回答

5
你可以使用类似于/((\.|\?|\!)\s)|(\?|\!)|(\.$)/g这样的表达式来获取元素。以下是每个捕获组的伪代码解释:
  1. ((\.|\?|\!)\s):任何以空格结尾的.?!
  2. (\?|\!):任何独立的?!
  3. (\.$):任何以行末结束.。(根据字符串,此步骤可能不必要)
以下是大致的代码,帮助你进入正确的轨道:

console.clear();
var str = 'This is a wordpress plugin. its older version was 2.3.4 and new version is 2.4. But the version 2.4 had a lot of bungs. Can we solve it?';
console.log('"' + str + '"');
console.log('Becomes:');
console.log('"' + str.replace(/((\.|\?|\!)\s)|(\?|\!)|(\.$)/g, ".\n") + '"');

"真正的交易"需要进行数轮替换,以考虑不同的符号:

console.clear();
var str = 'This is a wordpress plugin. its older version was 2.3.4 and new version is 2.4. But the version 2.4 had a lot of bungs. Can we solve it?';
str = str
  //"all"
  //.replace(/((\.|\?|\!)\s)|(\?|\!)|(\.$)/g,".\n")
  //"."
  .replace(/((\.)\s)|(\.$)/g, ".\n")
  //"?"
  .replace(/((\?)\s)|(\?)/g, "?\n")
  //"!"
  .replace(/((\!)\s)|(\!)/g, "!\n")
console.log(str)


1
不必要的话,如果你想返回正确的符号,你可以简单地传递一个函数来替换方法。例如:function(match){return match+"\n"})这将使它看起来像这样:console.log('"' + str.replace(/((.|?|!)\s)|(?|!)|(.$)/g, function(match){return match+"\n"}) + '"')甚至可以使用ECMA6箭头函数:console.log('"' + str.replace(/((.|?|!)\s)|(?|!)|(.$)/g, m=>m+"\n") + '"') - Arturas Tamulaitis
这段代码片段在这里运行得很正常。感谢您的回答,我也创建了这个表达式并解决了我的问题。str.replace(/([.?!])\s(?=[a-z]|[A-Z])/g, "$1|").split("|")* - Ahmad

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接