使用 Perl 匹配句子中的单词?

发布于 2024-12-20 13:59:52 字数 486 浏览 0 评论 0原文

我想在 Perl 中提取两个单词之间的单词,但我不知道我可以使用正则表达式或任何库来做到这一点吗?

例如:

$sen = "A short quick brown fox jumps over the lazy dog running in the market";

@sentence = split / /, $sen;
foreach my $word (@sentence) {

}        

我想获取 brownlazy 之间的单词以及左侧 2 个单词和右侧 2 个单词。

output:

words between: fox jumps over the
2 words from left: short quick
2 words from right: dog running

我怎样才能得到上面的输出?

i want to extract words between two words in perl but i dont know i can use regular expression or any lib to do that?

example:

$sen = "A short quick brown fox jumps over the lazy dog running in the market";

@sentence = split / /, $sen;
foreach my $word (@sentence) {

}        

i want to get the words between brown and lazy together with 2 words from the left and 2 words from the right.

output:

words between: fox jumps over the
2 words from left: short quick
2 words from right: dog running

how can i come up with the above output?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

七婞 2024-12-27 13:59:52

这是作业吗?如果是这样,那么您应该在问题中这么说,您得到的答案将旨在帮助您学习,而不是简单地提供解决方案。

您正在声明一个数组,其中一个元素包含整个句子字符串,包括开始和结束双引号。这不可能是你想要的,因为你的循环只会执行一次,并将 $word 设置为句子字符串。

您必须启动每个 Perl 程序以

use strict;
use warnings;

使调试更容易。

下面的代码执行您所描述的操作。

use strict;
use warnings;

my $sentence = "A short quick brown fox jumps over the lazy dog running in the market";
my @sentence = split ' ', $sentence;

my @sample = grep /fox/ .. /the/, @sentence;
print "words between: @sample\n";

@sample = @sentence[-2..-1];
print "2 words from right: @sample\n";

@sample = @sentence[0..1];
print "2 words from right: @sample\n";

输出

words between: fox jumps over the
2 words from right: the market
2 words from right: A short

Is this homework? If so then you should say so in your question and the answers you get will be aimed towards helping you to learn rather than simply offering a solution.

You are declaring an array with one element containing the entire sentence string, including the opening and closing double quotes. That cannot be what you intended as your loop will execute just once with $word set to the sentence string.

You must start every Perl program with

use strict;
use warnings;

to make debugging easier.

The code below does what you describe.

use strict;
use warnings;

my $sentence = "A short quick brown fox jumps over the lazy dog running in the market";
my @sentence = split ' ', $sentence;

my @sample = grep /fox/ .. /the/, @sentence;
print "words between: @sample\n";

@sample = @sentence[-2..-1];
print "2 words from right: @sample\n";

@sample = @sentence[0..1];
print "2 words from right: @sample\n";

OUTPUT

words between: fox jumps over the
2 words from right: the market
2 words from right: A short
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文