Powershell逐字读取文本文件 [英] Powershell Reading text file word by word
本文介绍了Powershell逐字读取文本文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
因此,我试图计算文本文件中的单词,但是当我获取内容时,数组会逐个字母地读取它们,因此不允许我逐个单词地对其进行比较.我希望你们能帮助我!
So I'm trying to count the words of my text file however when I do get-content the array reads them letter by letter and so it doesn't let me compare them word by word. I hope you guys can help me out!
清除主机 #功能
Clear-Host #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
推荐答案
您的脚本的功能,进行了一些
What your script does, edited down a bit:
$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(" ")
,使其成为单词而不是行的数组.
You probably wanted to do $poem = $poem.Split(" ")
to make it an array of words instead of lines.
或者您可以使用
function Get-Articles ($poem) {
...
Get-Articles $poem.Split(" ")
您可以通过以下方式使用PowerShell管道:
And you could make use of the PowerShell pipeline with:
$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"
这篇关于Powershell逐字读取文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文