請參考前面的問題。 如何通過id(從XML中得到的Id值)獲得替換,并放入CSV,powerhell中
我需要添加ForEach-Object而不是ForEach,我有11,000行。因此,它需要太多的時間。
foreach ($csvRow in$csvRows) {
foreach ($columnName in $columnNames) {
$id =$csvRow.$columnName.
if (-not $id) { continue }
$newId = @($xmlDoc.enum_types.enum_type。 Where( { $_.field_name -eq $columnName }, 'First')。)
items).ForEach( { $_.item }).Where( { $_.id -eq $id }).value
$csvRow.$columnName = $newId。
}
}
$csvRows | Export-Csv -NoTypeInformation -Encoding utf8 $CSVpath
uj5u.com熱心網友回復:
你可以做的一件事是在你的另一個問題中從 "enums "xml中預先計算你的查找結果。
原始代碼--7649毫秒
# setup
$xml = @"
<enum_types>
<enum_type field_name="Test1">
<items>
<專案>
<id>1</id>
<value>A</value>
</item>
</items>
</enum_type>
<enum_type field_name="Test2">
<專案>
<專案>
<id>1</id>
<value>A</value>
</item>
</items>
</enum_type>
</enum_types>
"@。
$enums = [xml] $xml;
$csv = @("Test1, Test2") 。
$csv = 1..110000 | % { "1, 1" }
$data = $csv | ConvertFrom-Csv
$columnNames = @( "Test1", "Test2" ) 。
# perf test - 7649 milliseconds[/span]。
measure-command -expression {
foreach ($csvRow in $data)
{
foreach ($columnName in $columnNames)
{
$id =$csvRow.$columnName.
if ( -not $id )
{
continue;
}
$newId = @($enums.enum_types.enum_type。 Where( { $_.field_name -eq $columnName }, 'First') 。
items).ForEach( { $_.item }).Where( { $_.id -eq $id }).value
$csvRow.$columnName = $newId。
}
}
}
使用預先計算的查找 - 792毫秒
使用預先計算的查找 - 792毫秒
# setup
... 如上述 ...
# pre-compute lookups(預計算查找)。
$lookups = @{};
foreach( $enum_type in $enums.enum_types.enum_type )
{
$lookups[$enum_type.field_name] = @{}。
foreach( $item in $enum_type.items.item )
{
$lookups[$enum_type.field_name][$item.id] =$item.value
}
}
Write-host ($lookups | convertto-json -depth 99)
# {
# "Test1": {
# "1": "A"
# },
# "Test2": {
# "1": "A"
# }
# }
# perf test - 792 milliseconds
measure-command -expression {
foreach ($csvRow in $data)
{
foreach ($columnName in $columnNames)
{
$id =$csvRow.$columnName.
if (-not $id)
{
continue;
}
$csvRow.$columnName = $lookups[$columnName][$id ]
}
}
}
你可能還能從這種方法中擠出更多的東西,但它已經有了10倍的速度(在我非常有限的基準測驗中)。
uj5u.com熱心網友回復:
將所有的新專案預加載到哈希表中:
$Types = $xmlDoc.enum_types.enum_type
$HashTable = @{}。
Import-Csv .1.Csv |ForEach-Object { $Names =$Null } {
if (!$Names) {
$Names = $_.psobject.Properties.Name
foreach ($Name in $Names) {
$HashTable[$Name] = @{}。
foreach ($Field in $Types.Where{$_.field_name -eq $Name}) {
foreach ($Item in $Field.Items.Item) {
$HashTable[$Name][$Item.Id] = $Item.Value
}
}
}
}
foreach ($Name in $Names) {
$id = $_.$Name.
If ($HashTable[$Name].Contains($Id) {
$_.$Name = $HashTable[$Name] [$Id]
}
}
$_" }
} |Export-Csv .1New.Csv -NoTypeInformation -Encoding utf8
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/310247.html
標籤:
上一篇:用Pandas讀取CSV的錯誤
下一篇:如何使用Powershell在csv中添加額外的';'(分號)或任何特殊字符,除了第一列和空單元格的值之外,所有的列都是如此。
