我想在只有两个单词的行上应用正则表达式。我的文件在括号中的单词之间有可变的空格数,如下所示:
Politician_name:(何塞·玛丽亚·阿斯纳尔·何塞·玛丽亚·阿斯纳尔·何塞·玛丽亚·阿斯纳尔·何塞·马里亚·阿斯纳尔·何塞·马里亚·阿斯纳尔);Politician_name:(托尼·布莱尔、托尼·布莱尔·托尼·布莱尔·托尼·布莱尔);
我想要一个输出:
Politician_name:(托尼·布莱尔,托尼·布莱尔,托尼·布莱尔,托尼·布莱尔,托尼·布莱尔,托尼·布莱尔,托尼·布莱尔,托尼·布莱尔,托尼·布莱尔,托尼·托尼,);
我的代码将正则表达式应用于每一行,并得到如下错误输出:
Politician_name:(何塞·玛丽亚·阿斯纳尔·何塞·玛丽亚·阿斯纳尔·何塞·玛丽亚·阿斯纳尔·何塞·马里亚·阿斯纳尔·何塞·马里亚·阿斯纳尔·何塞·马里亚·阿斯纳尔玛丽亚·何塞·何塞·何塞 );
这是我的密码:
use strict;
use warnings;
use Data::Dumper;
use utf8;
open(IN, $ARGV[0]) or die "Can't read file $ARGV[0]\n";
while (my $line=<IN>)
{
my ($pol,$value) = split(/:/, $line);
warn Dumper \$pol;
chomp($value);
$value=~ s/[ ]+/ /g;
$value=~ s/\);//g;
my $n;
$n = $1 if ($value =~ /\((.+?)\|/);
$n=~ m/(\w*)\s(\w*)/g;
my $swapname="$2 $1";
warn Dumper \$swapname;
print "$pol: $value | $swapname );\n";
}
close(IN); 我该怎么做才能停止处理三个字的名字?
发布于 2012-10-11 10:58:53
$n=~ m/(\w*)\s(\w*)/g; # Replace this regex with the one below使用下面的Regex与$n进行比较,还需要将其包含在一个if中,其他明智的方法是对每个输入执行打印:-
my $n;
$n = $1 if ($value =~ /\((.+?)\|/);
if ($n =~ m/^\s*(\w+)\s(\w+)\s*$/g) { # Notice `$` to mark the end of 2 words..
my $swapname="$2 $1";
warn Dumper \$swapname;
print "$pol: $value | $swapname );\n";
}但是,您没有考虑|之后的下一个值。你得这么做..。它只是取第一个值..。
因此,您的输出将是:-
Politician_name: (Tony Blair |tony blair | Tony Blair | tony blair | Blair Tony )第二tony blair没有被使用。您需要为此修改代码。
实际上,您需要一个循环来迭代每个名称,以使这段代码正常工作。
UPDATE :- 我宁愿将您的代码更改为:-
# You should always use lexical variables as file handles..
open my $fh, '<', 'D:\demo.txt' or die $!;
while (<$fh>) # Don't need use any extra variable here.. Default to $_
{
my ($pol,$value) = split /:/; # Do split on $_ by default
warn Dumper \$pol;
chomp($value);
$value=~ s/[ ]+/ /g;
$value=~ s/\((.*)\);/$1/g;
my @name = split(/\|/, $value); # Split your string to an array
# Filter out array to remove duplicate
my $_ = $name[0];
if (m/^\s*(\w+)\s(\w+)\s*$/g) {
# If first element contains 2 words, proceed with rest of the elements
print "($value "; # print the original string you want..
# Append to it later on the reverse of other array elements
foreach (@name) {
if (m/^\s*(\w+)\s(\w+)\s*$/g) {
my $swapname = "$2 $1";
warn Dumper \$swapname;
print "| $swapname "; # Print swapnames after $value
}
}
print ");\n"; # End the string..
}
}
close($fh);https://stackoverflow.com/questions/12837561
复制相似问题