所以我试图计算我的文本文件的单词但是当我获取内容时,数组会一个字母一个字母地读取它们,所以它不会让我一个词一个词地比较它们。我希望你们能帮帮我!

清除主机
#职能

function Get-Articles (){

 foreach($Word in $poem){
    if($Articles -contains $Word){
       $Counter++
    }
}
    write-host "The number of Articles in your sentence: $counter"
}

#Variables

$Counter = 0

$poem = $line
$Articles = "a","an","the"

#Logic

$fileExists = Test-Path "text.txt"

if($fileExists) {
    $poem = Get-Content "text.txt"
    }
else
    {
    Write-Output "The file SamMcGee does not exist"
    exit(0)
    }

$poem.Split(" ")

Get-Articles

最佳答案

你的脚本做了什么,稍微编辑了一下:

$poem = $line                    # set poem to $null (because $line is undefined)
$Articles = "a","an","the"       # $Articles is an array of strings, ok

                                 # check file exists (I skipped, it's fine)

$poem = Get-Content "text.txt"   # Load content into $poem,
                                 # also an array of strings, ok

$poem.Split(" ")                 # Apply .Split(" ") to the array.
                                 # Powershell does that once for each line.
                                 # You don't save it with $xyz =
                                 # so it outputs the words onto the
                                 # pipeline.
                                 # You see them, but they are thrown away.

Get-Articles                     # Call a function (with no parameters)


function Get-Articles (){

                                 # Poem wasn't passed in as a parameter, so
 foreach($Word in $poem){        # Pull poem out of the parent scope.
                                 # Still the original array of lines. unchanged.
                                 # $word will then be _a whole line_.

    if($Articles -contains $Word){    # $articles will never contain a whole line
       $Counter++
    }
}
    write-host "The number of Articles in your sentence: $counter"  # 0 everytime
}

您可能想要使用 $poem = $poem.Split(" ") 使其成为单词数组而不是行。

或者您可以将 $poem 单词传递给函数
function Get-Articles ($poem) {
...

Get-Articles $poem.Split(" ")

您可以通过以下方式使用 PowerShell 管道:
$Articles = "a","an","the"

$poemArticles = (Get-Content "text.txt").Split(" ") | Where {$_ -in $Articles}
$counter = $poemArticles | Measure | Select -Expand Count
write-host "The number of Articles in your sentence: $counter"

10-08 18:08