Perl:使用数组来大写单词

时间:2015-08-21 19:29:03

标签: string perl

我处理大块全文大写文本,将它们转换为混合大小写并添加标点符号。但是,我想要大写一大堆单词和名称,例如一周中的几天,几个月,一些人等等。

有没有办法以某种方式使用正确大写术语的数组或散列?所以,如果我有一个字符串"然后在星期一,我们应该看到bob和sue"将它转换为"然后在星期一,我们应该看到Bob和Sue"如果我将条款存储在数组或散列中?

谢谢!

2 个答案:

答案 0 :(得分:2)

use feature qw( fc );  # Alternatively, "lc" is "close enough".

my @to_capitalize = qw( Monday Bob Sue );
my @abbreviations = qw( USA );
my @exceptions    = qw( iPhone );

my %words = (
   ( map { fc($_) => ucfirst(lc($_)) } @to_capitalize ),
   ( map { fc($_) => uc($_)          } @abbreviations ),
   ( map { fc($_) => $_              } @exceptions ),
);

my $pat =
   join '|',
      #map quotemeta,    # If this is needed, our use of \b is incorrect.
         keys %words;

s/\b($pat)\b/$words{fc($1)}/ig;

根据需要进行调整。

答案 1 :(得分:0)

您可以创建单词的哈希值进行转换,然后如果遇到这些单词,则应用预期的转换:

use strict;
use warnings; 

use feature qw(say);

my %transformations = (
   monday => \&titlecase,
   bob    => \&titlecase,
   sue    => \&titlecase,
   shout  => \&uppercase,
);

while ( my $line = <$filehandle> ) {
   chomp $line;
   foreach my $word ( split /\s+/, $line ) {
      if ( my $transform = $transformations{lc $word} ) {
         $line =~ s/$word/$transform->($word)/ge;
      }
   }
   say $line;
}

sub titlecase {
   my ($s) = @_;

   return ucfirst lc $s;
}

sub uppercase {
   my ($s) = @_;

   return uc $s;
}