gpt4 book ai didi

arrays - PowerShell分类表存储哈希表

转载 作者:行者123 更新时间:2023-12-02 23:53:26 26 4
gpt4 key购买 nike

我有以下缩进文本结构的数据:

“学科”

\ t“类别”

\ t \ t“子类别”

e.g. for two records I would have 

"Planet of the Apes"
\t"Scifi"
\t\t"Movie"
\t\t"TV series"
\t"Popular"
\t\t"Remake"
\t\t"Cult Classic"

BBC News
\t"Topical"
\t\t"Daily News"
\t"Geographical"
\t\t"UK"
\t\t"England"

ITV News
\t"Topical"
\t\t"Daily News"
\t\t"UK"
\t"Geographical"
\t\t"UK"
\t\t"England"

(请原谅,由于Stackoverflow中的自动格式设置,所示的格式,制表符或空格分隔会变得有些困难!

我正在尝试找出将其转换为可以过滤和排序的最佳方法。由于数据当前是纯文本,因此我有一个if语句可以确定它是Subject,Category还是Subcategory,但是从这样的数据中构建哈希表的最明智的方法是什么?
$processedData = @{}
$versionattribs | ForEach-Object{
if($_ -match "^\s*$" -or $_ -match "Inherits.*")
{
# Is a blank line
}
elseif($_ -notmatch "`t")
{
# Is a Subject
Write-Host "Subject: $_ "
$Subject = $_
}
elseif($_ -match "`t" -and $_ -notmatch "`t`t")
{
# Is a category
Write-host "Category: $_"
$category = $_
}
elseif($_ -match "`t`t")
{
# Is a sub-category label
Write-Host "Label: $_ "
$label = $_
}
else
{
#Unexpected attribute
Write-host "Error - unexpected line indentation : $_"
}
}

最佳答案

我采用了您的方法,并使用了switch语句提供的内置功能:

$data = @{}
switch -Regex -File C:\Temp\weirddata.txt
{
'(^\s*$)|(Inherits)'
{
continue
}

"^[^`t]"
{
$subject = ($PSItem -replace '"').Trim()
$data[$subject] = @{}
continue
}

"^`t[^`t]"
{
$category = ($PSItem -replace '"').Trim()
$data[$subject][$category] = [System.Collections.Generic.List[string]]@()
continue
}

"^`t`t"
{
$label = ($PSItem -replace '"').Trim()
$data[$subject][$category].Add($label)
continue
}

default
{
Write-Warning "No match found for $PSItem"
}
}

$data

它查找示例提供的所有内容,并删除引号/空格。仅当您有重复的主题或同一主题下的类别时,它才会失败。

关于arrays - PowerShell分类表存储哈希表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52102099/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com