gpt4 book ai didi

python - PowerShell 在大型搜索/替换操作中很慢(比 Python 慢得多)?

转载 作者:IT老高 更新时间:2023-10-28 20:41:18 25 4
gpt4 key购买 nike

我有 265 个 CSV 文件,总记录(行)超过 400 万条,需要在所有 CSV 文件中进行搜索和替换。我在下面有一段 PowerShell 代码可以执行此操作,但执行该操作需要 17 分钟:

ForEach ($file in Get-ChildItem C:\temp\csv\*.csv) 
{
$content = Get-Content -path $file
$content | foreach {$_ -replace $SearchStr, $ReplaceStr} | Set-Content $file
}

现在我有以下 Python 代码,它执行相同的操作,但执行时间不到 1 分钟:

import os, fnmatch

def findReplace(directory, find, replace, filePattern):
for path, dirs, files in os.walk(os.path.abspath(directory)):
for filename in fnmatch.filter(files, filePattern):
filepath = os.path.join(path, filename)
with open(filepath) as f:
s = f.read()
s = s.replace(find, replace)
with open(filepath, "w") as f:
f.write(s)

findReplace("c:/temp/csv", "Search String", "Replace String", "*.csv")

为什么 Python 方法效率更高?是我的 PowerShell 代码效率低下,还是 Python 在文本操作方面只是一种更强大的编程语言?

最佳答案

试试这个 PowerShell 脚本。它应该表现得更好。由于文件是在缓冲流中读取的,因此 RAM 的使用也大大减少。

$reader = [IO.File]::OpenText("C:\input.csv")
$writer = New-Object System.IO.StreamWriter("C:\output.csv")

while ($reader.Peek() -ge 0) {
$line = $reader.ReadLine()
$line2 = $line -replace $SearchStr, $ReplaceStr
$writer.writeline($line2)
}

$reader.Close()
$writer.Close()

这会处理一个文件,但您可以使用它测试性能,如果更可接受,请将其添加到循环中。

或者,您可以使用 Get-Content 将多行读入内存,执行替换,然后使用 PowerShell 管道写入更新的 block 。

Get-Content "C:\input.csv" -ReadCount 512 | % {
$_ -replace $SearchStr, $ReplaceStr
} | Set-Content "C:\output.csv"

为了提高性能,您还可以像这样编译正则表达式(-replace 使用正则表达式):

$re = New-Object Regex $SearchStr, 'Compiled'
$re.Replace( $_ , $ReplaceStr )

关于python - PowerShell 在大型搜索/替换操作中很慢(比 Python 慢得多)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9724521/

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