如何修复“无法找到接受“ +”的位置参数”?

时间:2019-06-10 12:59:16

标签: powershell scripting

所以我要执行此任务,其中必须读取文件。 然后计算文件中每个单词出现的次数。 之后,必须将每个单词都写入另一个文件,并在该单词后面加上该单词出现的次数。

我已经有一些代码,但是我尝试的所有内容都遇到了错误, 我是新来的,我不明白很多错误消息。

Function AnalyseTo-Doc
{
    param ([Parameter(Mandatory=$true)][string]$Pad )
    New-Item C:\destination.txt -ItemType file
    $destination = "C:\destination.txt"
    $filecontents = get-content $Pad | Out-String

    foreach($hit in $filecontents)
    {
        #$tempWoord = $hit | Convert-String
        $lengte = $hit.Length
        if($lengte -ge 4)
        {
            $hits = get-content $Pad | Out-String
            if($hits -notcontains $hit)
            {
                Add-Content $destination $hit + $hit.LineNumber + '`n'
            }
            elseif($hits -contains $hit)
            {
                Add-Content $destination $hit + $hit.LineNumber + '`n'
            }
        }
    }
}

因此,如上所述,这是要做的:

  1. 它必须正确读取文件。
  2. 它必须知道单词是否超过4个字符。如果是这样,则必须计算在内
  3. 每个字数必须超过4个字符。
  4. 最后,每个单词都必须写到一个附加文件中,该文件中要说明单词本身及其后面的数字。

按次数计算,我的意思是:它在文本文件中出现了多少次

PS:我们正在测试.txt个文件

2 个答案:

答案 0 :(得分:1)

我知道这个问题已经有了答案,但是如果我们仅将连续的字母字符算作单词,并且您想要这些单词的总数,那么在没有字符例外的情况下,这应该可以工作。问题中的帖子似乎并没有真正算出单词。

Function AnalyseTo-Doc
{
    param ([Parameter(Mandatory=$true)][string]$Pad )

    New-Item C:\destination.txt -ItemType file
    $destination = "C:\destination.txt"
    $filecontents = Get-Content $Pad -Raw

    $words = ($filecontents | Select-String -Pattern "\b[A-Za-z]{4,}\b" -AllMatches).Matches.Value
    $words | Group-Object -NoElement | Foreach-Object {
        ("{0},{1}" -f $_.Count,$_.Name) | Add-Content -Path $destination
        }
}

答案 1 :(得分:0)

注意:由于问题是How do i fix “positional parameter cannot be found that accepts ”+“,所以我要回答这个问题。下面的答案不能解决在修复以下问题之后可能出现的其他问题。


您应该在错误消息中看到的内容如下:

PS C:\SO\56526906> Add-Content 'destination.txt' $a + $b + $c
Add-Content : A positional parameter cannot be found that accepts argument '+'.
At line:1 char:1
+ Add-Content 'destination.txt' $a + $b + $c
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Add-Content], ParameterBindingException
    + FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell.Commands.AddContentCommand

直接将您指向发生错误的行。在这种情况下,这是因为您要为Add-Content提供以下参数:

$destination
$hit
+
$hit.LineNumber
+
'`n'

尽管您应该仅添加目标和内容。您对Add-Content的调用应如下所示:

Add-Content $destination "$hit $($hit.LineNumber)"

请注意,您无需在Add-Content之后添加`n,因为会自动添加换行符。

相关问题