我的PowerShell程序存在问题,计算我正在使用的文件中的句子数。我使用以下代码:
foreach ($Sentence in (Get-Content file))
{
$i = $Sentence.Split("?")
$n = $Sentence.Split(".")
$Sentences += $i.Length
$Sentences += $n.Length
}
我应该得到的句子总数是61但是我得到71,有人可以帮我解决这个问题吗?我的句子也设置为零。
由于
答案 0 :(得分:0)
foreach ($Sentence in (Get-Content file))
{
$i = $Sentence.Split("[?\.]")
$Sentences = $i.Length
}
我编辑了你的代码。
您使用的.
需要进行转义,否则Powershell会将其识别为正则表达式dotall
表达式,这意味着“任何字符”
因此,您应该将字符串拆分为"[?\.]"
或类似字符。
答案 1 :(得分:0)
在计算句子时,你要找的是每个句子结束的地方。但是,拆分会返回围绕这些结束字符的句子片段集合,其末尾本身由元素之间的间隙表示。因此,句子数量将等于间隙数量,这比分割结果中的片段数量少一个。
当然,正如Keith Hill在上面的评论中指出的那样,当您可以直接计算结束时,实际的拆分是不必要的。
foreach( $Sentence in (Get-Content test.txt) ) {
# Split at every occurrence of '.' and '?', and count the gaps.
$Split = $Sentence.Split( '.?' )
$SplitSentences += $Split.Count - 1
# Count every occurrence of '.' and '?'.
$Ends = [char[]]$Sentence -match '[.?]'
$CountedSentences += $Ends.Count
}
test.txt
档案的内容:
Is this a sentence? This is a
sentence. Is this a sentence?
This is a sentence. Is this a
very long sentence that spans
multiple lines?
另外,要澄清Vasili's answer的注释:PowerShell -split
运算符默认将字符串解释为正则表达式,而.NET Split
方法仅适用于文字字符串值。 / p>
例如:
'Unclosed [bracket?' -split '[?]'
会将[?]
视为正则表达式字符类并与?
字符匹配,返回两个字符串'Unclosed [bracket'
和''
'Unclosed [bracket?'.Split( '[?]' )
会调用Split(char[])
重载并匹配每个[
,?
和]
字符,并返回三个字符串'Unclosed '
, 'bracket'
和''