gpt4 book ai didi

php - 在 PHP 中将一段分解成句子

转载 作者:可可西里 更新时间:2023-10-31 22:40:46 24 4
gpt4 key购买 nike

我一直在用

explode(".",$mystring)

将段落拆分成句子。然而,这不包括以不同标点符号结束的句子,例如! ? : ;

有没有办法使用数组而不是单个字符作为分隔符?或者,还有另一种使用各种标点符号拆分的巧妙方法吗?

我试过了

explode(("." || "?" || "!"),$mystring)

希望但它没有用......

最佳答案

您可以使用 preg_split() 结合 PCRE lookahead condition在每次出现 . 后拆分字符串, ; , : , ? , ! , .. 同时保持实际标点符号的完整性:

代码:

$subject = 'abc sdfs.    def ghi; this is an.email@addre.ss! asdasdasd? abc xyz';
// split on whitespace between sentences preceded by a punctuation mark
$result = preg_split('/(?<=[.?!;:])\s+/', $subject, -1, PREG_SPLIT_NO_EMPTY);
print_r($result);

结果:

Array
(
[0] => abc sdfs.
[1] => def ghi;
[2] => this is an.email@addre.ss!
[3] => asdasdasd?
[4] => abc xyz
)

您还可以为缩写词(Mr.、Mrs.、Dr...)添加一个黑名单,通过插入否定后视断言,这些缩写词应该被拆分成自己的句子:

$subject = 'abc sdfs.   Dr. Foo said he is not a sentence; asdasdasd? abc xyz';
// split on whitespace between sentences preceded by a punctuation mark
$result = preg_split('/(?<!Mr.|Mrs.|Dr.)(?<=[.?!;:])\s+/', $subject, -1, PREG_SPLIT_NO_EMPTY);
print_r($result);

结果:

Array
(
[0] => abc sdfs.
[1] => Dr. Foo said he is not a sentence;
[2] => asdasdasd?
[3] => abc xyz
)

关于php - 在 PHP 中将一段分解成句子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10494176/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com