将 space 替换为 0
substitute space to 0
使用 Perl,我只想将 space 替换为 0。空格由制表符 (\t) 分隔。提前致谢!例如:
1 2 2 5 4
4 4 4 4 3
4 4 1
1 5 6 4
至
1 2 0 0 2 0 5 0 0 0 4
4 4 4 0 0 4 0 0 0 3 0
0 0 4 4 0 0 1 0 0 0 0
0 1 5 6 0 4 0 0 0 0 0
我的代码:
use strict;
use warnings;
open(DATA,"DATA")||die"cannot open the file: $!\n";
while( <DATA> )
{
s/(^| \K)(?!\d)/0/g;
print;
}
出来了:
1 2 2 5 4
4 4 4 4 3
0 4 4 1
0 1 5 6 4
use strict;
use warnings qw( all );
use feature qw( say );
while (<>) {
chomp;
my @fields = split(/\t/, $_, -1);
for my $field (@fields) {
$field = 0 if $field eq "";
}
say join "\t", @fields;
}
不清楚"the space"是什么意思。以上将 empty 字段替换为零。选择以下最合适的:
if $field eq ""
(空)
if $field eq " "
(1 space)
if $field =~ /^[ ]+\z/
(1+ spaces)
if $field =~ /^[ ]*\z/
(0+ spaces)
if $field =~ /^\s+\z/
(1+白space)
if $field =~ /^\s*\z/
(0+白space)
很简单,
只需将文件的内容存储在变量 $x 中,然后找到匹配项并替换:
use strict;
use warnings;
my $filename = "c:\path\to\file.txt";
my $x;
open(my $fh, '<', $filename) or die "cannot open file $filename: $!";
{
local $/;
$x= <$fh>;
}
close($fh);
$x=~s/(\n )/\n0/g; #starting zeros
$x=~s/( \n)/ 0\n/g; #ending zeros
$x=~s/( $)/ 0\n/g; #last zero if no end line on end of string
$x=~s/(^ )/0/g; #first zero at beginning of string
$x=~s/( )/ 0/g; #zeros within the matrix
print $x;
使用 Perl,我只想将 space 替换为 0。空格由制表符 (\t) 分隔。提前致谢!例如:
1 2 2 5 4
4 4 4 4 3
4 4 1
1 5 6 4
至
1 2 0 0 2 0 5 0 0 0 4
4 4 4 0 0 4 0 0 0 3 0
0 0 4 4 0 0 1 0 0 0 0
0 1 5 6 0 4 0 0 0 0 0
我的代码:
use strict;
use warnings;
open(DATA,"DATA")||die"cannot open the file: $!\n";
while( <DATA> )
{
s/(^| \K)(?!\d)/0/g;
print;
}
出来了:
1 2 2 5 4
4 4 4 4 3
0 4 4 1
0 1 5 6 4
use strict;
use warnings qw( all );
use feature qw( say );
while (<>) {
chomp;
my @fields = split(/\t/, $_, -1);
for my $field (@fields) {
$field = 0 if $field eq "";
}
say join "\t", @fields;
}
不清楚"the space"是什么意思。以上将 empty 字段替换为零。选择以下最合适的:
if $field eq ""
(空)if $field eq " "
(1 space)if $field =~ /^[ ]+\z/
(1+ spaces)if $field =~ /^[ ]*\z/
(0+ spaces)if $field =~ /^\s+\z/
(1+白space)if $field =~ /^\s*\z/
(0+白space)
很简单, 只需将文件的内容存储在变量 $x 中,然后找到匹配项并替换:
use strict;
use warnings;
my $filename = "c:\path\to\file.txt";
my $x;
open(my $fh, '<', $filename) or die "cannot open file $filename: $!";
{
local $/;
$x= <$fh>;
}
close($fh);
$x=~s/(\n )/\n0/g; #starting zeros
$x=~s/( \n)/ 0\n/g; #ending zeros
$x=~s/( $)/ 0\n/g; #last zero if no end line on end of string
$x=~s/(^ )/0/g; #first zero at beginning of string
$x=~s/( )/ 0/g; #zeros within the matrix
print $x;