powershell - 我有一个 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
解决方案
正如 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)文件中。
推荐阅读
- python - CNN 对回归 Keras Tuner 的优化
- python - Flask-Sqlalchemy 中的字符串转数值
- python - 如何解决这些 ALSA 错误
- javascript - 如果 jQuery 函数没有在 `$(document),ready` 函数中定义,有没有办法使用它们?
- svelte - 来自现有 nodejs express 服务器的多个 sapper 应用程序
- swiftui - NavigationLink 从其子视图返回视图后不可点击
- python - 循环浏览消息集合时从一个用户集合中获取信息 - Firestore
- flutter - No Icon but it can be tested
- python - 使用 pandas.DataFrame.plot() 时如何显示所有 xticks?
- java - 有没有办法将外部文件“信息”保存到java中的数组中?