私はテキストファイルの単語を数えようとしていますが、取得すると配列は文字で1文字ずつ読み込まれるため、単語ごとに単語を比較することはできません。私はあなたが私を助けることができることを願っています!Powershell単語単位でテキストファイルを読む
$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(" ")
をやってみたかった:あなたのスクリプトは、少し下に編集したん何
クリアホスト #Functions
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
各単語でScriptblockが実行され、PowerShellではscriptblock呼び出しのオーバーヘッドが大きく、PSのパイプライン処理が遅くなるため、これはこれまでのところ最も遅い解決策です。最も速いものがコメントに記述されています: '(Select-String '\ b(a | an | the)\ b' text.txt -AllMatches).Matches.Count'。問題の元のコードは、各行またはテキスト内容の文字列全体で 'split'を使うことで修正されていれば、ほぼ速いです。 – wOxxOm