【发布时间】:2020-10-01 12:25:33
【问题描述】:
我有大量文件,我想对其中的单词进行分析 - 计算每个单词在每个文件中出现的频率。作为最终输出,我想要一个 CSV 文件,标题中包含文件名,每个文件有两列 - 单词和相应的计数。
file1 word, file1 count, file2 word, file2 count, ....
hello, 4, world, 5, ...
password, 10, save, 2, ...
为了实现这一点,我打开每个文件并将字数保存在哈希表中。 因为每个哈希表都有不同的长度(不同数量的唯一词),所以我尝试将结果放在数据表中以导出它们。
$file = Get-ChildItem -Recurse
$out = New-Object System.Data.DataSet "ResultsSet"
foreach($f in $file){
$pres = $ppt.Presentations.Open($f.FullName, $true, $true, $false)
$id = $f.Name.substring(0,5)
$results = @{} #Hash table for this file
for($i = 4; $i -le $pres.Slides.Count; $i++){
$s = $pres.Slides($i)
$shapes = $s.Shapes
$textBox = $shapes | ?{$_.TextFrame.TextRange.Length -gt 100}
if($textBox -ne $null){
$textBox.TextFrame.TextRange.Words() | %{$_.Text.Trim()} | %{if(-not $results.ContainsKey("$_")){$results.Add($_,1)}else{$results["$_"] += 1 }}
}
}
$pres.Close()
$dt = New-Object System.Data.DataTable
$dt.TableName = $id
[String]$dt.Columns.Add("$id Word")
[Int]$dt.Columns.Add("$id Count")
foreach($r in ($results.GetEnumerator() | sort Value)) {
$dt.Rows.Add($r.Key, $r.Value)
}
$out.Tables.Add($dt)
}
$out | export-csv
主要有两个问题:
- 每个文件的唯一字数不同(哈希表长度不同)
- 文件被逐一读取。因此,每个文件的结果需要在导出之前进行缓存。
不知何故,我没有得到我想要的输出,而只有元数据。如何获得正确的输出?
【问题讨论】:
-
那么如果你有 3 个文件,每个文件有 30 个唯一的单词,你希望最终得到 180 列吗?
-
使用
Export-Csv -NoTypeInformation阻止它显示元数据 -
@Doug:不。在这种情况下,我想要 6 列(3 次“单词”和“计数”),30 行。
-
@Theo -NoTypeInformation 只删除带有 TypeInformation 的第一行,而不是元数据输出。
-
然后向我们展示您当前的输出并更好地解释所需的输出应该是什么