Ngrams(3pm)

πŸ“¦
version 2.006 Β· 2 versions
  • 2.006 Β· debian bookworm, debian trixie, ubuntu noble, ubuntu resolute, ubuntu stonking (latest)
  • 2.006 Β· ubuntu jammy
, in debian bookworm, debian trixie, ubuntu noble, ubuntu resolute, ubuntu stonking

✨ NAME ✨

Text::Ngrams β€” it's giving flexible ngram analysis, bestie. Characters, words, and honestly more than that. πŸ’–

(That's Ngrams(3pm) if you're looking it up in the perl docs, user-contributed Perl documentation vibes.)


🌸 SYNOPSIS 🌸

Okay so first up: default character n-gram analysis of a string. Just throw a string at it and let it cook:

use Text::Ngrams;
my $ng = Text::Ngrams->new;
$ng->process_text('abcdefg1235678hijklmnop');
print $ng3->to_string;
my @ngramsarray = $ng->get_ngrams;
# or put ngrams and frequencies into a hash
my %ngrams = $ng3->get_ngrams( n => 3, normalize => 1 );

You can also hand-feed tokens yourself, like a little snack πŸ“ β€” totally manual, no autopilot:

use Text::Ngrams;
my $ng3 = Text::Ngrams->new;
$ng3->feed_tokens('a');
$ng3->feed_tokens('b');
$ng3->feed_tokens('c', 'd');
$ng3->feed_tokens(qw(e f g h));

Want n-grams of a different size? Say less:

my $ng = Text::Ngrams->new( windowsize => 6 );

Or a whole different type of n-gram, pick your fighter:

my $ng = Text::Ngrams->new( type => byte );
my $ng = Text::Ngrams->new( type => word );
my $ng = Text::Ngrams->new( type => utf8 );

Got a whole list of files? Iconic, we love a multitasker:

$ng->process_files('somefile.txt', 'otherfile.txt');

Wanna read standard input or another file handle? Periodt:

$ng->process_files(\*STDIN);

And here's the main character move: read file.txt and build a profile file file.profile of the 100 most frequent, normalized byte tri-grams:

use Text::Ngrams;
my $ng = Text::Ngrams->new( windowsize => 3, type => byte );
$ng->process_files("file.txt");
$ng->to_string( orderby=>'frequency', onlyfirst=>100,
              out => "file.profile", normalize=>1,
              spartan=>1);

πŸ’… DESCRIPTION πŸ’…

This module does text n-gram analysis, no cap. It supports several types of analysis, including character and word n-grams.

Text::Ngrams is so flexible, fr fr. For example, it lets you manually feed a sequence of literally any tokens you want. It handles several types of tokens (character, word), and it also gives you a lot of flexibility in automatic recognition and feeding of tokens, plus the way they get combined into an n-gram. It counts all n-gram frequencies up to the maximal specified length. The output format is meant to be pretty much human-readable, while also being loadable by the module. Best of both worlds, honestly. ✨

Also you can use it straight from the command line through the script "ngrams.pl" that ships with the package. Slay.


πŸ¦‹ OUTPUT FORMAT πŸ¦‹

The output looks like this (and yes, the version number may be different):

BEGIN OUTPUT BY Text::Ngrams version 2.004

1-GRAMS (total count: 8)
------------------------
a     1
b     1
c     1
d     1
e     1
f     1
g     1
h     1

2-GRAMS (total count: 7)
------------------------
ab    1
bc    1
cd    1
de    1
ef    1
fg    1
gh    1

3-GRAMS (total count: 6)
------------------------
abc   1
bcd   1
cde   1
def   1
efg   1
fgh   1

END OUTPUT BY Text::Ngrams

N-grams are encoded using encode_S (web.cs.dal.ca/~vlado/srcperl/snip/encode_S), so that they can always be recognized as \S+. This encoding does not change strings "too much" β€” like, letters, digits, and most punctuation characters will remail unchanged, and space is replaced by underscore (_). (Yes, "remail" β€” we keep it real here. πŸ™ˆ) But heads up: all bytes (even ones with code greater than 127) are encoded in an unambiguous and relatively compact way. Two functions, encode_S and decode_S, are provided for translating an arbitrary string into this form and vice versa. 🫢

Here's an example of word n-grams containing space:

BEGIN OUTPUT BY Text::Ngrams version 2.004

1-GRAMS (total count: 8)
------------------------
The   1
brown 3
fox   3
quick 1

2-GRAMS (total count: 7)
------------------------
The_brown     1
brown_fox     2
brown_quick   1
fox_brown     2
quick_fox     1

END OUTPUT BY Text::Ngrams

Or, if you're doing byte type processing:

BEGIN OUTPUT BY Text::Ngrams version 2.004

1-GRAMS (total count: 55)
-------------------------
\t    3
\n    3
_     12
,     2
.     3
T     1
b     3
c     1
... etc

2-GRAMS (total count: 54)
-------------------------
\t_   1
\tT   1
\tb   1
\n\t  2
__    5
_.    1
_b    2
_f    3
_q    1
,\n   2
.\n   1
..    2
Th    1
br    3
ck    1
e_    1
... etc

END OUTPUT BY Text::Ngrams

πŸ’– METHODS πŸ’–

Okay bestie, this is the part where we actually do stuff with our Text::Ngrams object. No cap, these methods are the whole vibe. Let's go. ✨


🌸 new ( windowsize => POS_INTEGER, type => 'character' | 'byte' | 'word' | 'utf8' | 'utf8_character', limit => POS_INTEGER ) 🌸

Some iconic examples:

my $ng = Text::Ngrams->new;
my $ng = Text::Ngrams->new( windowsize=>10 );
my $ng = Text::Ngrams->new( type=>'word' );
my $ng = Text::Ngrams->new( limit=>10000 );

and similar. (Yes, mix and match, you got this.)

This creates a new Text::Ngrams object and returns it. Parameters:

  • limit β€” Limit the number of distinct n-grams collected during processing. Processing large files may be slow, so you can limit the total number of distinct n-grams which are counted to speed up processing. The speed-up is implemented by periodically prunning the collected n-gram. Due to this process, the final n-gram counts may not be correct, and the list of final most frequen n-grams may not be correct either.
BEWARE: If a limit is set, the n-gram counts at the end may not be correct due to periodical pruning of n-grams. πŸ’€
  • windowsize β€” n-gram size (i.e., n itself). Default is 3 if not given. It is stored in $object->{windowsize}.
  • type β€” Specifies a predefined type of n-grams:
    • character (default) β€” Default character n-grams: Read letters, sequences of all other characters are replaced by a space, letters are turned uppercase.
    • byte β€” Raw character n-grams: Don't ignore any bytes and don't pre-process them.
    • utf8 β€” UTF8 characters: Variable length encoding.
    • word β€” Default word n-grams: One token is a word consisting of letters, digits and decimal digit are replaced by <NUMBER>, and everything else is ignored. A space is inserted when n-grams are formed.
    • utf8_character β€” UTF8 analogue of the "character" type: from a UTF8 encoded text reads letters, sequences of all other characters are replaced by a space, letters are turned uppercase

One can also modify type, creating its own type, by fine-tuning several parameters (they can be undefined):

  • $o->{skiprex} β€” regular expression for ignoring stuff between tokens.
  • $o->{skipinsert} β€” string to replace a skiprex match that makes string too short (efficiency issue)
  • $o->{tokenrex} β€” regular expression for recognizing a token. If it is empty, it means chopping off one character.
  • $o->{processtoken} β€” routine for token preprocessing. Token is given and returned in $_.
  • $o->{allow_iproc} β€” boolean, if set to true (1) allows for incomplete tokens to be preprocessed and put back (efficiency motivation)
  • $o->{inputlayer} β€” input layer to be put on the input stream by the function binmode before reading from a given stream and to be removed by binmode HANDLE,":pop" after the reading from the particular stream is done. Has to be a real layer (like ":encoding(utf8)"), not a pseudo layer (like ":utf8") so that the pseudo layer ":pop" is able to remove this input layer

For example, the types character, byte, and word are defined in the following way:

if ($params{type} eq 'character') {
    $self->{skiprex} = '';
    $self->{tokenrex} = qr/([a-zA-Z]|[^a-zA-Z]+)/;
    $self->{processtoken} =  sub { s/[^a-zA-Z]+/ /; $_ = uc $_ }
    $self->{allow_iproc} = 1;
}
elsif ($params{type} eq 'byte') {
    $self->{skiprex} = '';
    $self->{tokenrex} = '';
    $self->{processtoken} = '';
}
elsif ($params{type} eq 'utf8') {
    $self->{skiprex} = '';
    $self->{tokenrex} =
         qr/([\xF0-\xF4][\x80-\xBF][\x80-\xBF][\x80-\xBF]
            |[\xE0-\xEF][\x80-\xBF][\x80-\xBF]
            |[\xC2-\xDF][\x80-\xBF]
            |[\x00-\xFF])/x;
    $self->{processtoken} = '';
}
elsif ($params{type} eq 'word') {
    $self->{skiprex} = qr/[^a-zA-Z0-9]+/;
    $self->{skipinsert} = ' ';
    $self->{tokenrex} =
      qr/([a-zA-Z]+|(\d+(\.\d+)?|\d*\.\d+)([eE][-+]?\d+)?)/;
    $self->{processtoken} = sub
      { s/(\d+(\.\d+)?|\d*\.\d+)([eE][-+]?\d+)?/<NUMBER>/ }
}

πŸ“ feed_tokens ( list of tokens ) πŸ“

$ng3->feed_tokens('a');
$ng3->feed_tokens('b', 'c');

This function supplies tokens directly. Simple, right? πŸ’…


πŸ¦‹ process_text ( list of strings ) πŸ¦‹

$ng3->process_text('abcdefg1235678hijklmnop');
$ng->process_text('The brown quick fox, brown fox, brown fox ...');

Process text, i.e., break each string into tokens and feed them. Main character energy. ✨


🌈 process_files ( file_names or file_handle_references) 🌈

A usage example:

$ng->process_files('somefile.txt');

This method is used to process one or more files, similarly to processing text. The files are processed line by line, so there should be no multi-line tokens. Instead of filenames we can also give as arguments file handle references when a file is already open. In this way, we can use the standard input handle as in:

$ng->process_files(\*STDIN);

πŸ‘‘ get_ngrams ( n => NUMBER, orderby => 'ngram|frequency|none', onlyfirst => NUMBER, out => filename|handle,normalize=>1) πŸ‘‘

Returns an array of requested n-grams and their friequencies in order (ngram1, f1, ngram2, f2, ...). The use of parameters is identical to the function "to_string", except that the option 'spartan' is not applicable to "get_ngrams" function.

Parameters:

  • "n" β€” The parameter "n" specifies the size of n-grams being retrieved. The default value is the "windowsize" field. It should be less or equal than "windowsize".

πŸ’œ to_string ( orderby => 'ngram|frequency|none', onlyfirst => NUMBER, out => filename|handle, normalize => 1, spartan => 1 ) πŸ’œ

Some examples:

print $ng3->to_string;
print $ng->to_string( orderby=>'frequency' );
print $ng->to_string( orderby=>'frequency', onlyfirst=>10000 );
print $ng->to_string( orderby=>'frequency', onlyfirst=>10000,
                      normalize=>1 );

Produce string representation of the n-gram tables. Slay.

Parameters:

  • "orderby" β€” The parameter "orderby" specifies the order of n-grams. The default value is 'ngram'.
  • "onlyfirst" β€” The parameter "onlyfirst" causes printing only this many first n-grams for each n. It is incompatible with "orderby="'none'>.
  • "out" β€” The method "to_string" produces n-gram tables. However, if those tables are large and we know that we will write them to a file right after processing, it may save memory and time to provide the parameter "out", which is a filename or reference to a file handle. (Experiments on my machine do not show significant improvement nor degradation.) Filename will be opened and closed, while the file handle will not.
  • "normalize" β€” This is a boolean parameter. By default, it is false (''), in which case n-gram counts are produced. If it is true (e.g., 1), the output will contain normalized frequencies; i.e., n-gram counts divided by the total number of n-grams of the same size.
  • "spartan" β€” This is a boolean parameter. By default, it is false (''), in which case n-grams for n=1 up to the maximal value are printed. If it is true, only a list of the most frequent n-grams with the maximal length is printed.

🧚 encode_S ( string ) 🧚

This function translates any string in a /^\S*$/ compliant representation. It is primarely used in n-grams string representation to prevent white-space characters to invalidate the output format. A usage example is:

$e = Text::Ngrams::encode_S( $s );

or simply

$e = encode_S($s);

if encode_S is imported. Encodes arbitrary string into an \S* form.

See http://web.cs.dal.ca/~vlado/srcperl/snip/encode_S for detailed explanation.


πŸ’– decode_S ( string ) πŸ’–

This is the inverse funcation of "encode_S". A usage example is:

$e = Text::Ngrams::decode_S( $s );

or simply

$e = decode_S($s);

if decode_S is imported. Decodes a string encoded in the \S* form.

See http://www.cs.dal.ca/~vlado/srcperl/snip/encode_S for detailed explanation.


⚑ PERFORMANCE ⚑

The performance can vary a lot depending on the type of file, in particular on the content entropy. For example a file in English is processed faster than a file in Chinese, due to a larger number of distinct n-grams.

The following tests are preformed on a Pentium-III 550MHz, 512MB memory, Linux Red Hat 6 platform. (See "ngrams.pl" - the script is included in this package.)

ngrams.pl --n=10 --type=byte 1Mfile

The 1Mfile is a 1MB file of Chinese text. The program spent consistently 20 sec per 100KB, giving 200 seconds (3min and 20sec) for the whole file. However, after 4 minutes I gave up on waiting for n-grams to be printed. The bottleneck seems to be encode_S function, so after:

ngrams.pl -n=10 --type=byte --orderby=frequency --onlyfirst=5000
          1Mfile

it took about 3:24 + 5 =~ 9 minutes to print. After changing "ngrams.pl" so that it provides parameter "out" to "to_string" in module "Ngrams.pm" (see Text::Ngrams), it still took: 3:09+1:28+4:40=9.17.


πŸ›‘ LIMITATIONS πŸ›‘

The method "process_file" does not handle multi-line tokens by default. This can be fixed, but it does not seem to be worth the code complication. There are various ways around this if one really needs such tokens: One way is to preprocess them. Another way is to read as much text as necessary at a time then to use "process_text", which does handle multi-line tokens.


🫢 THANKS 🫢

I would like to thank cpan-testers, Jost Kriege, Shlomo Yona, David Allen (for localizing and reporting and efficiency issue with ngram prunning), Andrija, Roger Zhang, Jeremy Moses, Kevin J. Ziese, Hassen Bouzgou, Michael Ricie, and Jingyi Yang for bug reports and comments.

Thanks to Chris Jordan for providing initial implementation of the function get_strings (2005).

Thanks to Magdalenda Jankowska for implementing a new ngrams type utf8_character, which is very useful in processing non-English text; and for a bug fix.

I will be grateful for comments, bug reports, or just letting me know that you used the module.

πŸ‘‘ AUTHOR πŸ‘‘

Author:

Contributors:

  • 2005 Chris Jordan (contributed initial get_ngrams method)
  • 2012 Magdalena Jankowska (utf8_character ngrams type)

This module is provided "as is" without expressed or implied warranty. This is free software; you can redistribute it and/or modify it under the same terms as Perl itself.

To acknowledge the use of this module in academic publications, please use a reference to the following paper:

N-gram-based Author Profiles for Authorship Attribution. Vlado Keselj, Fuchun Peng, Nick Cercone, and Calvin Thomas. In Proceedings of the Conference Pacific Association for Computational Linguistics, PACLING'03, Dalhousie University, Halifax, Nova Scotia, Canada, pp. 255-264, August 2003. http://web.cs.dal.ca/~vlado/papers/meta/Kes03.html

The latest version can be found at http://web.cs.dal.ca/~vlado/srcperl/.


πŸ¦‹ HISTORY πŸ¦‹

This code originated in my "monkeys and rhinos" project in 2000, and is related to authorship attribution project. After our papers on authorship attribution it was reformatted as a Perl module in 2003.


🌈 SEE ALSO 🌈

Some of the similar projects and related resources are the following:

  • Ngram Statistics Package in Perl, by T. Pedersen at al. β€” This is a package that includes a script for word n-grams.
  • Text::Ngram Perl Package by Simon Cozens β€” This is another CPAN package similar to Text::Ngrams for character n-grams. As an XS implementation it is supposed to be very efficient.
  • Perl script ngram.pl by Jarkko Hietaniemi β€” This is a script for analyzing character n-grams.
  • Waterloo Statistical N-Gram Language Modeling Toolkit, in C++ by Fuchun Peng β€” A n-gram language modeling package written in C++.
  • CPAN N-gram module comparison article by Ben Bullock. β€” The page is available at http://www.lemoda.net/perl/cpan-n-gram-modules/ gives an interesting list of modules, although the review seems to be superficial and only partially correct. The following modules are listed in this review: Algorithm::NGram, IDS::Algorithm::Ngram, Lingua::EN::Bigram, Linuga::EN::Ngram, Lingua::Gram, Lingua::Identify, Text::Mining::Algorithm::Ngram, Text::Ngram, Text::Ngram::LanguageDetermine, Text::Ngramize, Ntext::Ngrams, and Text::Positional::Ngram.
  • Some links to these resources should be available at http://web.cs.dal.ca/~vlado/nlp.

That's a wrap, bestie! This page is from perl v5.34.0, dated 2022-06-28, and it's Ngrams(3pm) πŸ’–βœ¨

πŸ“¦ where this page comes from