【问题标题】:Perl - how to convert a string that contains a space-separated words into a hashPerl - 如何将包含空格分隔的单词的字符串转换为哈希
【发布时间】:2013-05-22 17:17:49
【问题描述】:

有人可以帮我如何将包含空格分隔的单词的字符串转换为散列,其中散列键是字符串中的单词,散列值是散列中单词的出现次数?

谢谢

【问题讨论】:

  • 显示您的输入和输出示例。
  • @mpapec:没有示例,问题描述似乎很清楚,但很高兴看到一些解决方案的尝试。
  • 尝试自己编写一些东西,如果不起作用,请将其带给我们以帮助您。您启动它,我们提供帮助。我们不是为你写的。向我们展示您尝试过的实际代码,然后我们可以从那里帮助您。如果您先自己尝试一下,您可能会非常接近答案。

标签: perl


【解决方案1】:

这样的?

use strict;
use warnings;
use Data::Dumper;

my $string = "foo bar baz foo bar foo bar quux";
my %count;
$count{$_}++ for split /\s+/, $string;

print Dumper( \%count );

输出:

$VAR1 = {
          'bar' => 3,
          'baz' => 1,
          'quux' => 1,
          'foo' => 3
        };

【讨论】:

    【解决方案2】:
      $string = "do re me fa so la te do";
    
      for $word ( split " +", $string )
         {
         $word_count{$word}++;
         }
    
      for $word ( keys %word_count )
         {
         print "$word\t$word_count{$word}\n";
         }
    

    我更喜欢“+”而不是“\s+”,因为后者会切掉所有空白。你特别提到了空格,所以我只想剪掉实际的空格。

    【讨论】:

    • 不是我最喜欢的,但它是我工作场所的标准(来自 Whitesmiths),所以现在是习惯了。
    猜你喜欢
    • 2017-01-06
    • 1970-01-01
    • 2019-03-07
    • 1970-01-01
    • 1970-01-01
    • 2014-07-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-02
    相关资源
    最近更新 更多