gpt4 book ai didi

perl - 动态解析 BibTeX 并创建哈希的哈希

转载 作者:行者123 更新时间:2023-12-01 02:29:58 25 4
gpt4 key购买 nike

我正在尝试解析以下 BibTeX 文件(bibliography.bib):

@book{Lee2000a,
abstract = {Abstract goes here},
author = {Lee, Wenke and Stolfo, Salvatore J},
title = {{Data mining approaches for intrusion detection}},
year = {2000}
}
@article{Forrest1996,
abstract = {Abstract goes here},
author = {Forrest, Stephanie and Hofmeyr, Steven A. and Anil, Somayaji},
title = {{Computer immunology}},
year = {1996}
}

我正在使用 BibTeX::Parser包按预期工作,问题在于创建哈希结构的哈希。这是我的代码:
#!/usr/bin/perl
# http://search.cpan.org/~gerhard/BibTeX-Parser-0.62/lib/BibTeX/Parser.pm
use BibTeX::Parser;
use IO::File;
use Data::Dumper;
use strict;
use warnings;

my $filename="bibliography.bib";
my (%bibliography, %article);
my $i;
my ($entry, @entries, $type, $key);
my (my $hkey, my $hvalue);

# open BibTeX
my $fh = IO::File->new("$filename") or die "could not open $filename: $!\n";

# create parser object ...
my $parser = BibTeX::Parser->new($fh);

# ... and iterate over entries
while ($entry = $parser->next ) {
if ($entry->parse_ok) {

# return BibTeX elements like abstract, author, title ...
@entries = $entry->fieldlist();

# create %article as a hash array e.g. year -> 1996; isbn -> 1581138709 etc.
foreach (@entries) {
$article{"$_"} = $entry->field("$_");
}

# return article's key (Lee2000a, Forrest1996)
$key = $entry->key;

# append %article into %bibliography with approporiate key
$bibliography{"$key"} = \%article;

#Debug
#print $entry->key, "\n";
#print Dumper (\%article);

# removes all elements of %article (prepare for next iteration)
%article = ();

#Debug
#print "================================\n";
}

else {
warn "Error parsing file: " . $entry->error;
}
}

#Debug
#print Dumper (\%bibliography);
Dumper (\%bibliography) 的当前输出:
$VAR1 = {
'Lee2000a' => {},
'Forrest1996' => $VAR1->{'Lee2000a'}
};
Dumper (\%bibliography) 的期望输出:
$VAR1 = {
'Lee2000a' => {
'abstract' => 'Abstract goes here',
'author' => 'Lee, Wenke and Stolfo, Salvatore J'
'title' => 'Data mining approaches for intrusion detection'
'year' => '2000'
},
'Forrest1996' => {
'abstract' => 'Abstract goes here',
'author' => 'Forrest, Stephanie and Hofmeyr, Steven A. and Anil, Somayaji'
'title' => 'Computer immunology'
'year' => '1996'
}
};

我在做什么错?非常感谢。

最佳答案

在没有这一行的情况下尝试您的代码:

# removes all elements of %article (prepare for next iteration)
%article = ();

您已将 $bibilography{$key} 设置为对该哈希的引用,然后将其清空。

此外,将 %article 的声明移到循环中(可能就在 if ($entry->parse_ok) { 之后,以便其作用域在您使用它的地方是本地的,并且不需要重新初始化它。

希望有帮助...

更新以包含排序问题...这应该可以对您的哈希进行排序:
foreach my $bib_key ( sort keys %bibliography ) {
print "$bib_key\n";

foreach my $article_key (sort keys %{ $bibliography{$bib_key} }) {
print "\t $article_key: $bibliography{$bib_key}{$article_key}\n";
}
}

关于perl - 动态解析 BibTeX 并创建哈希的哈希,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13764320/

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