我有一个包含 60 个值的平面文件(以 csv 分隔),需要用 60 个不同的新值替换。
Original_Value1 ---> New_Value1
Original_Value2 ---> New_Value2
Original_Value3 ---> New_Value3
Original_Value4 ---> New_Value4
.... 到 60。
该文件有超过 200k 个条目,其中 60 个值需要更改。实现这一目标的最有效方法是什么?
这是示例代码:
$input = 'input.txt';
$output = 'output.txt';
if ($fpin = fopen($input, 'r')) {
if ($fpout = fopen($output, 'a')) {
while ($data = fread($fpin, 1024)) {
fwrite($fpout, your_replacement_function($data));
}
fclose($fpout);
}
fclose($fpin);
}
珀尔。至少那是我的建议,应该能够在一条线上做到这一点......类似于
open( IN, " < filename.csv ");
open( OUT, " > output.csv ");
while (<IN>) { # reads in each line of the file
$line =~ s/Original_Value1/New_Value1/gi; # g is for global, i is to ignore case
$line =~ s/Original_Value2/New_Value2/gi; # g is for global, i is to ignore case
$line =~ s/Original_Value3/New_Value3/gi; # g is for global, i is to ignore case
# ... continue to your values... probably a better way of doing this from a file, but this is quick and dirty, and should work
print OUT $line; # prints out $line to the output file.
}
close(IN);
close(OUT);
无论如何,这已经很接近了,我已经有一段时间没有编写 perl 了,它可能会被擅长 PERL 高尔夫的人优化为几个字符... =)
假设
1) 新旧值的长度可能不同
2)您不知道哪些行包含要提前更改的值
使用 fgetcsv() 逐行遍历文件,检查该行中的字段,根据需要进行替换。使用 fputcsv() 将该行写回另一个文件