in reply to find acronyms in a text

This should work for text files.
#!/usr/bin/perl -w use strict; my %acronyms_captured; my $file = 'test.txt'; open FH, "<", $file or die; while(<FH>){ my @words = $_ =~ m/\b[A-Z]+\b/g; foreach(@words) { $acronyms_captured{$_} = undef; } } close(FH); foreach(keys(%acronyms_captured)){ print "$_\n"; }

Replies are listed 'Best First'.
Re^2: find acronyms in a text
by davorg (Chancellor) on Jul 23, 2009 at 14:59 UTC
    my @words = $_ =~ m/\b[A-Z]+\b/g;

    Aren't you missing capturing brackets there?

    my @words = m/\b([A-Z]+)\b/g;
    foreach(@words) { $acronyms_captured{$_} = undef; }

    Personally, I'd write that as:

    @acronyms_captured{@words} = ();

    I like hash slices a lot :-)

    --

    See the Copyright notice on my home node.

    Perl training courses

      well, i thought it didnt matter in this case either way as whatever is captured here is what i want ... but i guess adding capturing brackets to make it explicit is better practise.
      ... and also the same with using ( ) for undef
      am learning ... thanks
Re^2: find acronyms in a text
by steph_bow (Pilgrim) on Jul 23, 2009 at 14:44 UTC

    Thanks a lot, but I don't understand the line

    my @words = $_ =~ m/\b[A-Z]+\b/g;

    You don't use split ?

      Thanks a lot, but I don't understand the line  my @words = $_ =~ m/\b[A-Z]+\b/g;

      I used regular expressions here to capture all consecutively appearing upper case alphabets separated by word boundaries (\b). Please check the perl regular expressions documentation

      You don't use split ?

      You could use split if you like but i think it is better to split by \W+ (non-word character) rather than \s+. This helps keep pattern matching simple in the next step. For the sample text below, using \s+ instead of \W+ would find none unless we perform a more complicated pattern matching later.

      my %acronyms; my $text= "An important class of transcription factors called general +transcription factors (GTF) are necessary for transcription to occur. + The Most common GTF's are TFIIA, TFIIB, and TFIIE.And a few more not + mentioned here."; my @words = split('\W+', $text); foreach(@words) { if($_ =~ m/^[A-Z]+$/){ $acronyms{$_}++; } } foreach( keys(%acronyms) ){ print "$_ seen $acronyms{$_} times\n"; }