2016-11-04 67 views
0

因此,我將讀主機的輸入數據轉換爲一個數組,我想它可以讓我計算句子$ a中的單詞從$陣列。然而伯爵++不給我一個總Powershell - 我如何在我的數組中計數發生次數

function Get-Sentence($a){ 
       if($a -contains $array) { 
        $Count++ 
       } 
      else { 
        return 0 
       } 
     } 
     Write-Host "There are $count words" 

     [array]$Array = @("a", "an", "the") 
     [array]$a = Read-Host "Enter a long sentence from a story book or novel: ").split(" ") 
+0

'-contains'不工作的方式。你問的是拆分數組是否包含你指定的整個單詞數組,這顯然不是(它包含單詞,而不是數組)。你可以用循環來解決這個問題,或者通過將你的單詞列表存儲爲散列表並檢查其中的成員資格來更有效地解決問題。 –

+0

感謝您的快速響應,所以您在說我應該將我的$ Array數組放入哈希表中? – SkullNerd

回答

2

首選的方法:

最簡單的方式準確地計算多子的出現大概是:

上的任何一個匹配
  1. 構建正則表達式模式子字符串
  2. 使用-split運算符分割字符串
  3. 計算字符串的結果數量和。減去1:

# Define the substrings and a sentence to test against 
$Substrings = "a","an","the" 
$Sentence = "a long long sentence to test the -split approach, anticipating false positives" 

# Construct the regex pattern 
# The \b sequence ensures "word boundaries" on either side of a 
# match so that "a" wont match the a in "man" for example 
$Pattern = "\b(?:{0})\b" -f ($Substrings -join '|') 

# Split the string, count result and subtract 1 
$Count = ($Sentence -split $Pattern).Count - 1 

輸出:

C:\> $Count 
2 

正如你可以看到它已經匹配和拆分 「」 和 「」,而不是 「一個」 在上「期待」。

我會離開的運動轉換成該功能向讀者


注: 如果你開始喂不僅僅是簡單的ASCII字符串作爲輸入更多的,你可能需要之前逃離他們利用它們在模式:

$Pattern = "\b(?:{0})\b" -f (($Substrings |ForEach-Object {[regex]::Escape($_)}) -join '|') 

原始的方法:

如果您對正則表達式感到不舒服,您可以假定兩個空格之間的任何內容都是「一個單詞」(就像在您的原始示例中一樣),然後遍歷句子中的單詞並檢查是否爲陣列包含問題的字(而不是其他方式):

$Substrings = "a","an","the" 
$Sentence = (Read-Host "Enter a long sentence from a story book or novel: ").Split(" ") 

$Counter = 0 

foreach($Word in $Sentence){ 
    if($Substrings -contains $Word){ 
     $Counter++ 
    } 
} 

由於suggested by Jeroen Mostert,你也可以利用哈希表。有了這個,你可以跟蹤每個單詞的出現,而不只是一個總數:

$Substrings = "a","an","the" 
$Sentence = (Read-Host "Enter a long sentence from a story book or novel: ").Split(" ") 

# Create hashtable from substrings 
$Dictionary = @{} 
$Substrings |ForEach-Object { $Dictionary[$_] = 0 } 

foreach($Word in $Sentence){ 
    if($Dictionary.ContainsKey($Word)){ 
     $Dictionary[$Word]++ 
    } 
} 

$Dictionary 
+0

感謝您的快速響應!我不明白''\ b(?:{0})\ b「'部分是怎麼回事。有什麼方法可以用我的腳本編寫的方式來使用它嗎? – SkullNerd

+0

@BartVanRooijen'\ b(?:sometext)\ b'是一個正則表達式模式 - 「{0}」是一個佔位符。 '-f'運算符將用右邊的第一個參數替換'{0}'。 當你說「以我的腳本編寫方式使用它」時,你究竟是什麼意思?例如'-contains'運營商在這方面沒有任何意義 –

+0

非常感謝! – SkullNerd

1
$Substrings = "a","an","the" 
    ("a long long sentence to test the -split approach, anticipating false positives" -split " " | where {$Substrings -contains $_}).Count