从特定单词中的字符串中提取句子

时间:2019-05-17 15:35:34

标签: javascript node.js

我有一些像下面这样的长文本

  

大家好。我的名字是詹姆斯!   告诉我你的名字?所以我问你...

尝试找到单词名称,并返回包含该单词的句子

  • 我叫詹姆斯
  • 告诉我你的名字

我想走很长一段路(在循环之前在索引之前找到索引并寻找新行,点或问号等),但这看起来效率不高!

有没有更快的方法来实现这一目标?

1 个答案:

答案 0 :(得分:2)

本质上,您需要使用与句子匹配的正则表达式,将其在句子之间进行拆分以构成句子数组,然后通过检查句子中是否包含提供的单词来过滤数组。

请注意,此函数要求输入字符串使用正确的大小写和标点符号。

// The input string
let input = "Hello everyone. My name is James! Tell me your names? So I'd greet you..."

// Our function that finds sentences that include a given word
// Input: Word - The word you want to find
// Input: Text - The text you'll be searching through
// Output: An array of sentences from our text input that include the word input
function getSentencesWithWord(word, text) {
  // Search for sentences, insert a pipe, then split on the pipe
  const sentenceArray = text.replace(/([.?!])\s*(?=[A-Z])/g, "$1|").split("|")

  // Filter our array by checking if each sentence includes the word, then immedietly returns it
  return sentenceArray.filter(sentence => sentence.includes(word))
}

// Run a test of our function
console.log(getSentencesWithWord('name', input))

感谢@YanFoto引用了this答案的评论。


编辑

以下是正则表达式的简短说明,摘自上面链接的帖子:

  

1)查找标点符号(。或?或!之一)并将其捕获

     

2)标点符号可以在其后包含空格。

     

3)标点符号后,我希望输入一个大写字母。

     

与以前提供的正则表达式不同,这会正确   匹配英语语法。

     

从那里:

     

4)我们通过添加管道来替换捕获的标点符号|

     

5)我们将管道分开以创建句子数组。

如果您想在句子开头添加对其他非英语特殊字符的支持,则必须调整正则表达式。当前,我们的比赛中仅包含A-Z,但是如果添加À-ȕ,我们也可以包含特殊字符。总体而言,我们最终会遇到这样的情况,/([.?!])\s*(?=[A-ZÀ-ȕ])/g

请注意,我使用非英语字符的经验有限,可能需要进行调整以仅允许使用大写非英语字符。