gpt4 book ai didi

grammar - 如何引用语法中先前匹配的项目?

转载 作者:行者123 更新时间:2023-12-02 15:11:18 24 4
gpt4 key购买 nike

我正在尝试解析 BibTeX 作者字段,并将其拆分为单独的作者。这将帮助我重写每个作者的姓名首字母。这是一个最小的例子:

use v6;

my $str = '{Rockhold, Mark L and Yarwood, RR and Selker, John S}';

grammar BibTexAuthor {
token TOP {
<all-text>
}
token all-text {
'{' <authors> '}'
}
token authors {
[<author> [' and ' || <?before '}'>]]+
}
token author {
[<-[\s}]> || [' ' <!before 'and '>]]+
}
}

class BibTexAuthor-actions {
method TOP($/) {
say $/;
print "First author = ";
say $<author>.made[0];
make $/.Str;
}
method all-text($/) {
make $/.Str;
}
method authors($/) {
make $/.Str;
}
method author($/) {
make $/.Str;
}
}
my $res = BibTexAuthor.parse( $str, actions => BibTexAuthor-actions.new).made;

输出:

「{Rockhold, Mark L and Yarwood, RR and Selker, John S}」
all-text => 「{Rockhold, Mark L and Yarwood, RR and Selker, John S}」
authors => 「Rockhold, Mark L and Yarwood, RR and Selker, John S」
author => 「Rockhold, Mark L」
author => 「Yarwood, RR」
author => 「Selker, John S」
First author = Nil

为什么我无法在 TOP 方法中提取第一作者?

最佳答案

Why am I not able to extract the first author in the TOP method?

因为您并没有真正在操作方法中提取任何数据。您所做的只是将匹配的字符串附加到 $/.made 中,这实际上并不是您最终想要的数据。

如果您最终希望有不同的作者,您应该在 authors 操作方法中创建一个作者数组。例如:

use v6;

my $str = '{Rockhold, Mark L and Yarwood, RR and Selker, John S}';

grammar BibTexAuthor {
token TOP {
<all-text>
}
token all-text {
'{' <authors> '}'
}
token authors {
[<author> [' and ' || <?before '}'>]]+
}
token author {
[<-[\s}]> || [' ' <!before 'and '>]]+
}
}

class BibTexAuthor-actions {
method TOP($/) {
make { authors => $<all-text>.made };
}
method all-text($/) {
make $/<authors>.made;
}
method authors($/) {
make $/<author>».made;
}
method author($/) {
make $/.Str;
}
}
my $res = BibTexAuthor.parse( $str, actions => BibTexAuthor-actions.new).made;

say $res.perl;

打印

${:authors($["Rockhold, Mark L", "Yarwood, RR", "Selker, John S"])}

所以现在顶级匹配的 .made 是一个哈希,其中 authors 键保存一个数组。如果您想访问第一作者,您现在可以说

say $res<authors>[0];

获取Rockhold,Mark L

关于grammar - 如何引用语法中先前匹配的项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47248329/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com