【问题标题】:Powershell - What is the best way to extract sentences from stringPowershell - 从字符串中提取句子的最佳方法是什么
【发布时间】:2026-01-05 20:10:02
【问题描述】:

我有很多行的文本,结构是这样的。

Sentence a. Sentence b part 1 `r`n
sentence b part 2. Sentence c.`r`n
Sentence d. Sentence e. Sentence f. `r`n
....

我想将这些句子和部分提取到每个部分或句子的单个字符串数组中。 到目前为止,我找到了这些东西。

第一种方式。

$mySentences = $lineFromTheText -split "(?<=\.)"

第二种方式。

$mySentences = [regex]::matches($lineFromTheText, "([^.?!]+[.?!])?([^.?!]*$)?") | % {$_.Groups[1,2].Value} | % { If (-not ($_ -eq "")) {$_}}

还有第三个代码。

$mySentences = ($lineFromTheText | Select-String -Pattern "([^.?!]+[.?!])?([^.?!]*$)?" -AllMatches).Matches  | % {$_.Groups[1,2].Value} | % { If (-not ($_ -eq "")) {$_}}

似乎所有这些代码对我的作用与我所期望的一样,但我想知道自己在这么多这些方式中应该使用哪些代码。我的意思是什么是最好的代码。 请告诉我知道。 谢谢。

【问题讨论】:

  • “最佳代码”取决于您未提供的指标。您想要最短的执行时间吗?最少字节的源代码?最好的人类可读代码?最少的内存使用?他们都是?如果是这样,哪个指标应该具有哪个权重?
  • 根据KISS,你会选择第一个解决方案;-)
  • 性能效率怎么样
  • 仍然模棱两可,CPU 性能与内存性能?如果您正在寻找最快的方法,请参阅下面的答案。

标签: string powershell text-extraction


【解决方案1】:

如果您想要最少的执行时间,您可以衡量它。让我们将每个解决方案运行 10000 次,看看需要多长时间:

$lineFromTheText = "Sentence d. Sentence e. Sentence f."

(Measure-Command {1..10000 | % {$mySentences = $lineFromTheText -split "(?<=\.)"}}).Ticks
(Measure-Command {1..10000 | % {$mySentences = [regex]::matches($lineFromTheText, "([^.?!]+[.?!])?([^.?!]*$)?") | % {$_.Groups[1,2].Value} | % { If (-not ($_ -eq "")) {$_}}}}).Ticks
(Measure-Command {1..10000 | % {$mySentences = ($lineFromTheText | Select-String -Pattern "([^.?!]+[.?!])?([^.?!]*$)?" -AllMatches).Matches  | % {$_.Groups[1,2].Value} | % { If (-not ($_ -eq "")) {$_}}}}).Ticks

输出(示例):

1059468
14512767
20444350

看起来您的第一个解决方案最快,而您的第三个解决方案最慢。

【讨论】:

    最近更新 更多