首页 > 解决方案 > 我有一个 powershell 脚本,可以计算单词出现的次数。我如何显示每个单词位于哪一行?

问题描述

所以这个脚本计算单词在整个文件中出现的次数。
哪个完美。
现在我需要它来显示每个超过 4 个字符的单词出现在哪一行。
问题是我几乎没有编写脚本的经验。

感谢 AdminOfThings 为我提供了当前代码!

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
        }
}
AnalyseTo-Doc

标签: powershellscripting

解决方案


正如 AnsgarWiechers 所暗示的,Select-String 返回一个结构化对象,每行匹配数。

## Q:\Test\2019\06\11\SO_56543125.ps1
Function AnalyseTo-Doc{
    param ([Parameter(Mandatory=$true)][string]$Pad )

    $Lines = Select-String -Path $Pad -Pattern '\b[A-Za-z]{4,}\b' -AllMatches
    $Words = ForEach($Line in $Lines){
        ForEach($Match in $Line.Matches){
            [PSCustomObject]@{
                LineNumber = $Line.LineNumber
                Word       = $Match.Value
            }
        }
    }
    $Words | Group-Object Word | ForEach-Object {
        [PSCustomObject]@{
            Count= $_.Count
            Word = $_.Name
            Line = $_.Group.LineNumber -join ','
        }
    }
}

AnalyseTo-Doc Question_SO_56543125.txt

使用文件中的问题文本,Question_SO_56543125.txt脚本将返回:

> Q:\Test\2019\06\11\SO_56543125.ps1

Count Word          Line
----- ----          ----
    1 this          1
    1 script        1
    1 counts        1
    1 many          1
    1 times         1
    1 words         1
    1 appear        1
    1 whole         1
    1 file          1
    2 Which         2,3
    1 works         2
...snip...

输出可以很容易地保存在(csv)文件中。


推荐阅读