如何使用 Perl 匹配句子中的连续单词?
除了此方法之外,是否有更好的方法来匹配单词,我正在尝试查找数组中出现在任何句子中的单词。
my $count = 0;
my @strings = (
"i'm going to find the occurrence of two words going if possible",
"i'm going to find the occurrence of two words if impossible",
"to find a solution to this problem",
"i will try my best for a way to match this problem"
);
@neurot = qw(going match possible);
my $com_neu = '\b'.join('\b|\b', @neurot).'\b';
foreach my $sentence (@string){
@l = $sentence =~ /($com_neu)/gi;
foreach my $list (@l){
if($list =~ m/\w['\w-]*/){
print $list;
$count++;
}
}
print $count;
}
输出:
String 1: going going possible
String 2: going
String 3:
String 4: match
请帮助我更快的方法。
谢谢。
Is there better way to match words other than this method, im trying to find the word in the array that occur in any of the sentences.
my $count = 0;
my @strings = (
"i'm going to find the occurrence of two words going if possible",
"i'm going to find the occurrence of two words if impossible",
"to find a solution to this problem",
"i will try my best for a way to match this problem"
);
@neurot = qw(going match possible);
my $com_neu = '\b'.join('\b|\b', @neurot).'\b';
foreach my $sentence (@string){
@l = $sentence =~ /($com_neu)/gi;
foreach my $list (@l){
if($list =~ m/\w['\w-]*/){
print $list;
$count++;
}
}
print $count;
}
Output:
String 1: going going possible
String 2: going
String 3:
String 4: match
please help me with a faster way.
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
另一种方法可能是使用散列来匹配单词:
对于您提供的数据,此方法速度快约 7%。但请记住,数据集非常小,所以 YMMV。
Another approach could be to use hash to match the words:
For data you provided this method is ~ 7% faster. But keep in mind that the data set is very small, so YMMV.
“智能匹配”运算符怎么样?
foreach 我的 $elem (@neurot){
if(/$elem/i ~~ @strings){
打印“找到$ elem \ n”;
}
}
what about the 'smart-match' operator?
foreach my $elem (@neurot){
if(/$elem/i ~~ @strings){
print "Found $elem\n";
}
}
与 bvr 答案相同,但可能更清晰
The same as bvr answer, but perhaps cleaner