0

我正在尝试使用 XML::Simple 解析 XML 文件,以计算特定标签的出现(即特定于在整个文件中重复的标题的不同城市位置的出现,以便对数字进行进一步分析产生。例如:

<XML>
   <title> Teacher </title>
   <state> TX </state>
   <city> Dallas </city>

   <title> Teacher </title>
   <state> CA </state>
   <city> Los Angeles </city>

   <title> Engineer </title>
   <state> NY </state>
   <city> Manhattan </city>

   <title> Engineer </title>
   <state> NY </state>
   <city> Manhattan </city>
</XML>

我不知何故需要计算标题出现的次数和不同的位置,所以

教师:2 城市:2

工程师:2 城市:1

是)我有的:

    #!/usr/bin/env perl

    use XML::Simple;
    use Data::Dumper; 

    # initialize variables
    my $counter = 0;
    my @titlelist = ();
    my @citylist = ();

    # create object
    $xml = new XML::Simple;

    # read XML file
    my $jobs = $xml->XMLin("sample.xml");

    print Dumper($jobs);

    foreach my $titles(@{$jobs->{job}}) {
        push(@citylist, $titles->{city});
        push(@titlelist, $titles->{title});
    }

    print "@titlelist\n";
    print "@citylist\n";

我知道这是超级基本的,我还没有真正制作过任何东西,这是因为我是一个初学者,完全不知道如何从逻辑上解决这个问题。我真的需要帮助来理解我需要用来获得类似这样的输出的结构,并且希望任何指向正确方向的指针。我现在基本上只是将结果推送到数组中。我是否应该进行字符串比较,并基于该增量城市和标题计数器?我需要一个多维数组吗?任何想法都会有所帮助...谢谢!

4

1 回答 1

0

我可以尝试为您指明正确的方向。

首先,我将假设您的 xml<job>在每个作业周围都有标签,实际上看起来像这样

<XML>
    <job>
        <title> Teacher </title>
        <state> TX </state>
        <city> Dallas </city>
     </job>

现在,我将建议在您的下一段代码中重命名变量,以便更清楚地了解发生了什么

my $xml_data = $xml->XMLin("sample.xml");

# We want the list of things with the "<job>" tag 
my $jobs = $xml_data->{job}; 

print Dumper($jobs);   # this will now print a list (an arrayref)

# Now we look at each job in the list of jobs
# You can read this in english as "for each job in jobs"
foreach my $job (@$jobs) {
    # each $job has a city and title:
    print "here is a job in the city $job->{city} with the title $job->{title}\n";
}

那应该可以帮助你一些。在这一点上,您将不得不阅读 Perl 中的哈希是如何工作的。解决方案看起来像这样,但如果你还没有理解哈希,它就没有意义。

$num_jobs_for{ $title } ++;
$num_jobs_for_title_in_city{ $title }{ $city } ++

祝你好运!当您走得更远时,请随时再次发布。

于 2014-11-24T07:08:13.047 回答