arrays - Powershell逐字读取文本文件

标签 arrays powershell line

因此,我正在尝试计算我的文本文件的字数,但是当我执行 get-content 时,数组会逐个字母地读取它们,因此它不允许我逐字比较它们。希望大家帮帮我!

清除主机 #函数

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 words 传递给函数
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"

关于arrays - Powershell逐字读取文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40433898/

相关文章:

r - 绘制带有颜色渐变的 geom_segment 线? (或者有另一种强调开始与结束的方法吗?)

c++ - 在函数 : 2d array received is pointer array 中传递二维数组

c++ - 如何在 .h 和 .cpp 中为类中的私有(private)字符数组编写 get 函数?

windows - 如何使用 Powershell 编辑快捷方式中的 Target 属性以在文件路径后包含一个字符?

powershell - 在多个组中使用 Get-ADGroup 和 Get-Groupmember

javascript - Canvas - 旋转路径

java - 使用多线程在数组中查找质数

ios - 使用 swift 3 将数组添加到 Realm

math - PowerShell 数学问题?

Java 用线条分隔组件