将文本末尾的句号分割会创建一个空字符串。

3

给定以下文本

var text="unicorns! and rainbows? and, cupcakes.Hello this is splitting by sentences. However, I am not sure.";

我希望在每个句号处进行分割,如果句子结尾有句号,则将其分割成空字符串。

(4) ["unicorns! and rainbows? and, cupcakes", "Hello this is splitting by sentences", " However, I am not sure", ""]

什么是使用“.”拆分文本的好方法,但要考虑到文本结尾的情况?

1
在结尾处使用.filter(Boolean),这将删除任何空字符串。 - mhodges
为什么不直接检查最后一个字符串是否为空,如果是,则将其删除? - Ben Jones
3个回答

3
您可以使用.filter(Boolean)来过滤掉任何空字符串,就像这样:

var text="unicorns! and rainbows? and, cupcakes.Hello this is splitting by sentences. However, I am not sure.";
var splitText = text.split(".");
var nonEmpty = splitText.filter(Boolean);
// var condensed = text.split(".").filter(Boolean);
console.log(nonEmpty);

这可能看起来是一种奇怪的方法,但它既简单又高效,其概念如下:

var arr = ["foo", "bar", "", "baz", ""];
var nonEmpty = arr.filter(function (str) {
  return Boolean(str);
});

这里使用强制转换的方法来判断字符串是否为空。唯一能被强制转换为 false 的字符串值是空字符串 ""。所有其他字符串值都会被强制转换为 true。这就是为什么我们可以使用 Boolean 构造函数来检查一个字符串是否为空。
此外,如果你想要去除每个句子前后的空格,可以使用 .trim() 方法,像这样:

var text="unicorns! and rainbows? and, cupcakes.Hello this is splitting by sentences. However, I am not sure.";
var nonEmpty = text.split(".").filter(Boolean).map(str => str.trim());
console.log(nonEmpty);


0
这就是 String#split 的工作原理(而且这种方式很合乎逻辑)。字符串中的 . 后面没有任何内容,因此应该是一个空字符串。如果你想要从数组中去除空字符串,可以使用 Array#filter 进行过滤(使用箭头函数使其更简单):
var result = text.split(".").filter(s => s);       // an empty string is falsy so it will be excluded

或者可以一次性使用简单的正则表达式和String#match方法,例如:

var result = text.match(/[^.]+/g);                 // matches any sequence of character that are not a '.'

例子:

var text="unicorns! and rainbows? and, cupcakes.Hello this is splitting by sentences. However, I am not sure.";

var resultFilter = text.split(".").filter(x => x);
var resultMatch = text.match(/[^.]+/g);

console.log("With filter:", resultFilter);
console.log("With match:", resultMatch);


0

split 中添加 filter(Boolean) 确实是一种解决方法,但问题可以通过直接(且灵活地)给 split 提供一个正则表达式来处理。

例如,您可以使用忽略所有句点的正则表达式或保留所有句点(或其他标点符号)的正则表达式进行拆分:

const text = "unicorns! and rainbows? and, cupcakes.Hello this is splitting by sentences. However, I am not sure.";

// discard periods
console.log(text.match(/[^.]+/g));

// discard periods and leading whitespace
console.log([...text.matchAll(/(.+?)(?:\.\s*)/g)].map(e => e[1]));

// keep periods
console.log(text.match(/(.+?)\./g));

// keep periods periods but trim whitespace
console.log([...text.matchAll(/(.+?\.)\s*/g)].map(e => e[1]));

// discard various sentence-related punctuation
console.log(text.match(/[^.?!]+/g));


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