Powershell - 如何计算数组中的计数出现次数

时间:2016-11-04 16:36:54

标签: arrays powershell

所以我把读取主机的输入变成了一个数组,它让我可以计算从$ Array看到的单词$ a中的单词的次数。但是Count ++并没有给我一个总数

   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(" ")

2 个答案:

答案 0 :(得分:2)

首选方法:

准确计算多个子串出现次数的最简单方法可能是:

  1. 构造与任何一个子串相匹配的正则表达式模式
  2. 使用-split运算符拆分字符串
  3. 计算结果字符串数并减去1:
  4. # 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
    

    正如你所看到的,它将匹配并分裂为“a”和“the”,而不是“预期”中的“an”。

    我会把这个转换成一个功能练习给读者

    注意:  如果您开始提供的不仅仅是简单的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,您还可以使用HashTable。通过这种方式,您可以跟踪每个单词的出现次数,而不仅仅是总计数:

    $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
    

答案 1 :(得分:1)

public function deleteAction($id)
{
  $em = $this->getDoctrine()->getManager();

  $gig = $this->getDoctrine()
      ->getRepository('GoetzBundle\Entity\Gig')
      ->findOneById($id);

  ...

  foreach ($gig->getArtists() as $artist) {
      $gig->removeArtist($artist);
  }

  $em->persist($gig);
  $em->flush();

  ...
}