如何编写健壮的Perl脚本,该脚本将为arXiv ID生成BibTeX条目?
我的猜测是,我应该使用arXiv API并将其响应解析为XML::Atom。它应该为我提供构建BibTeX条目所需的信息。
这是我的开始方式:
use LWP::UserAgent;
use Text::BibTeX::Entry;
use XML::Atom;
my $arxivid = "hep-ph/9609357";
my $url = "http://export.arxiv.org/api/query?search_query=" . $arxivid . "&start=0&max_results=1";
my $browser = LWP::UserAgent->new();
my $response = $browser->get($url);
my $entry = Text::BibTeX::Entry->new();
也欢迎不使用arXiv API或XML :: Atom的答案。
这里是使用XML::TWig
解析下载的XML文件的起点:
XML::TWig
输出:
use feature qw(say);
use strict;
use warnings;
use LWP::UserAgent;
use Text::BibTeX;
use Text::BibTeX::Entry;
use XML::Twig;
use DateTime::Format::Strptime;
{
my $arxivid = "hep-ph/9609357";
my $url = "http://export.arxiv.org/api/query?search_query=" . $arxivid . "&start=0&max_results=1";
my $browser = LWP::UserAgent->new();
my $response = $browser->get($url);
my $xml = $response->content;
my $twig = XML::Twig->new->parse( $xml );
my $title = $twig->get_xpath ( '//entry/title',0 )->text;
my @authors;
for my $node ( $twig->findnodes( '//entry/author/name' )) {
push @authors, $node->text;
}
my $doi = $twig->get_xpath ( '//entry/link[@title="doi"]',0 )->att('href');
my $published = $twig->get_xpath ( '//entry/published',0 )->text;
my ( $year, $month) = parse_published( $published) ;
my $entry = Text::BibTeX::Entry->new();
$entry->set_metatype(BTE_REGULAR);
$entry->set_type('article');
$entry->set_key('article1');
$entry->set( 'title', $title );
$entry->set( 'author', join ' and ', @authors );
$entry->set( 'year', $year );
$entry->set( 'month', $month );
$entry->set( 'doi', $doi );
$entry->print(\*STDOUT);
}
sub parse_published {
my ( $published) = @_;
my $parser = DateTime::Format::Strptime->new(
pattern => '%FT%T%Z',
time_zone => 'UTC',
on_error => 'croak',
);
my $dt = $parser->parse_datetime($published);
return ( $dt->year, $dt->month_name);
}