请问用perl怎么统计每一行中某个单词出现的位置?譬如说,how old **are** you?where **are** you from?“are”这个单词在第一行是第三个,第二行是第二个,我想得到的是3 how old **are** you?2 where **are** you from
来源:学生作业帮助网 编辑:作业帮 时间:2024/08/17 03:32:02
![请问用perl怎么统计每一行中某个单词出现的位置?譬如说,how old **are** you?where **are** you from?“are”这个单词在第一行是第三个,第二行是第二个,我想得到的是3 how old **are** you?2 where **are** you from](/uploads/image/z/7114344-24-4.jpg?t=%E8%AF%B7%E9%97%AE%E7%94%A8perl%E6%80%8E%E4%B9%88%E7%BB%9F%E8%AE%A1%E6%AF%8F%E4%B8%80%E8%A1%8C%E4%B8%AD%E6%9F%90%E4%B8%AA%E5%8D%95%E8%AF%8D%E5%87%BA%E7%8E%B0%E7%9A%84%E4%BD%8D%E7%BD%AE%3F%E8%AD%AC%E5%A6%82%E8%AF%B4%2Chow+old+%2A%2Aare%2A%2A+you%3Fwhere+%2A%2Aare%2A%2A+you+from%3F%E2%80%9Care%E2%80%9D%E8%BF%99%E4%B8%AA%E5%8D%95%E8%AF%8D%E5%9C%A8%E7%AC%AC%E4%B8%80%E8%A1%8C%E6%98%AF%E7%AC%AC%E4%B8%89%E4%B8%AA%2C%E7%AC%AC%E4%BA%8C%E8%A1%8C%E6%98%AF%E7%AC%AC%E4%BA%8C%E4%B8%AA%2C%E6%88%91%E6%83%B3%E5%BE%97%E5%88%B0%E7%9A%84%E6%98%AF3+how+old+%2A%2Aare%2A%2A+you%3F2+where+%2A%2Aare%2A%2A+you+from)
请问用perl怎么统计每一行中某个单词出现的位置?譬如说,how old **are** you?where **are** you from?“are”这个单词在第一行是第三个,第二行是第二个,我想得到的是3 how old **are** you?2 where **are** you from
请问用perl怎么统计每一行中某个单词出现的位置?
譬如说,how old **are** you?
where **are** you from?
“are”这个单词在第一行是第三个,第二行是第二个,我想得到的是
3 how old **are** you?
2 where **are** you from?
请问用perl怎么统计每一行中某个单词出现的位置?譬如说,how old **are** you?where **are** you from?“are”这个单词在第一行是第三个,第二行是第二个,我想得到的是3 how old **are** you?2 where **are** you from
利用正则:
my $line = 'how old are you?';
$line /(.)\bare\b/ or die "Can't match\n"; # 匹配are,\b为单词边界;
my $string = $1; # 捕获括号中的内容,也就是are之前的内容;
my $n = $string s/ //g; # 将前面的空格换成空,返回成功个数;
print $n+1 ," $line\n"; # 前面的空格数加1就是are单词的位置;
当然,如果你认为用空格数判断单词个数不严谨,也可以改成带字符边界的正则,这里就不多说了.
#!/usr/bin/perl -w
use strict;
my @words;
while (<>) {
@words = split;
my $i = 1;
foreach my $word (@words) {
print "$i @words\n",if $word =~ /are/;
$i += 1;
}
}