0

各ドキュメントでの単語の出現をカウントするように設計された次の機能を実行している一連のドキュメントがあります。この関数はコンソールへの出力で正常に機能しますが、情報を含むテキストファイルを生成したいのですが、リスト内の各単語にファイル名が追加されています。

私の現在のコンソール出力は次のとおりです。

"processing document1 with x unique words occuring as follows"
"word1     12"
"word2      8"
"word3      3"
"word4      4"
"word5      1"

この形式の区切りファイルが必要です。

document1;word1;12
document1;word2;8  
document1;word3;3
document1;word4;4
document1;word1;1
document2;word1;16
document2;word2;11 
document2;word3;9
document2;word4;9
document2;word1;13 

以下の関数は単語と出現箇所のリストを取得しますが、各行の先頭に印刷されるようにfilename変数をどこにまたはどのように挿入するかを理解するのに苦労しています。MSDNはあまり役に立ちませんでした。変数を挿入しようとすると、ほとんどの場所でエラーが発生します(以下を参照)。

function Count-Words ($docs) {
    $document = get-content $docs 
    $document = [string]::join(" ", $document)        
    $words = $document.split(" `t",[stringsplitoptions]::RemoveEmptyEntries)                             
    $uniq = $words | sort -uniq  
    $words | % {$wordhash=@{}} {$wordhash[$_] += 1}
    Write-Host $docs "contains" $wordhash.psbase.keys.count "unique words distributed as follows."
    $frequency = $wordhash.psbase.keys | sort {$wordhash[$_]}
    -1..-25 | %{ $frequency[$_]+" "+$wordhash[$frequency[$_]]} | Out-File c:\out-file-test.txt -append
    $grouped = $words | group | sort count

出力ファイルコマンドレットに渡す文字列を作成する必要がありますか?これは私が最後の数回の試みで間違った場所に置いてきたものですか?なぜそれが特定の場所で起こっているのかを理解したいと思います。out-file選択した結果を達成するために どこに置くべきかわからないので、今は推測しているだけです。

-$docsとを使用して、PowerShellヘルプごとにコマンドをフォーマットしようとしまし-FilePathたが、上記に正常に実行されるものを追加するたびにout-file、次のエラーが発生します。

Out-File : Cannot validate argument on parameter 'Encoding'. The argument "c:\out-file-test.txt" does not bel
ong to the set "unicode,utf7,utf8,utf32,ascii,bigendianunicode,default,oem" specified by the ValidateSet attribute. Sup
ply an argument that is in the set and then try the command again.
At C:\c.ps1:39 char:71
+     -1..-25 | %{ $frequency[$_]+" "+$wordhash[$frequency[$_]]} | Out-File <<<<  -$docs -width 1024 c:\users\x46332\co
unt-test.txt -append
    + CategoryInfo          : InvalidData: (:) [Out-File], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.OutFileCommand
4

3 に答える 3

1

私はあなたのコードのほとんどを書き直しました。オブジェクトを利用して、必要に応じて簡単に書式設定できるようにする必要があります。これは「スペース」で分割し、単語をグループ化します。これを試して:

Function Count-Words ($paths) {
    $output = @()
    foreach ($path in $paths) {
        $file = Get-ChildItem $path 
        ((Get-Content $file) -join " ").Split(" ", [System.StringSplitOptions]::RemoveEmptyEntries) | Group-Object | Select-Object -Property @{n="FileName";e={$file.BaseName}}, Name, Count | % { 
            $output += "$($_.FileName);$($_.Name);$($_.Count)" 
        }
    }
    $output | Out-File test-out2.txt -Append
}

$filepaths = ".\test.txt", ".\test2.txt"

Count-Words -paths $filepaths

あなたが尋ねたように出力します(ドキュメント;単語;カウント)。documentname に拡張子を含めたい場合は、 に変更$file.BaseName$file.Nameます。テスト出力:

test;11;1
test;9;2
test;13;1
test2;word11;5
test2;word1;4
test2;12;1
test2;word2;2
于 2013-02-15T14:12:33.597 に答える
0

これを試して:

$docs = @("document1", "document2", ...)

$docs | % {
  $doc = $_
  Get-Content $doc `
    | % { $_.split(" `t",[stringsplitoptions]::RemoveEmptyEntries) } `
    | Group-Object `
    | select @{n="Document";e={$doc}}, Name, Count
} | Export-CSV output.csv -Delimiter ";" -NoTypeInfo

これを関数にしたい場合は、次のようにします。

function Count-Words($docs) {
  foreach ($doc in $docs) {
    Get-Content $doc `
      | % { $_.split(" `t",[stringsplitoptions]::RemoveEmptyEntries) } `
      | Group-Object `
      | select @{n="Document";e={$doc}}, Name, Count
  }
}

$files = @("document1", "document2", ...)

Count-Words $files | Export-CSV output.csv -Delimiter ";" -NoTypeInfo
于 2013-02-15T14:38:21.390 に答える
0

少し異なるアプローチ:

function Get-WordCounts ($doc)
{
      $text_ = [IO.File]::ReadAllText($doc.fullname)

      $WordHash = @{}

      $text_ -split '\b' -match '\w+'|
        foreach {$WordHash[$_]++}

      $WordHash.GetEnumerator() | 
       foreach {
         New-Object PSObject -Property @{
                                          Word     = $_.Key
                                          Count    = $_.Value
                                         }
               }
  }


$docs = gci c:\testfiles\*.txt |
 sort name

 &{
 foreach ($doc in dir $docs)
        {
           Get-WordCounts $doc |
           sort Count -Descending |
            foreach {
              (&{$doc.Name;$_.Word;$_.Count}) -join ';'  
             }
        }
} | out-file c:\somedir\wordcounts.txt
于 2013-02-15T16:00:13.597 に答える