That is a very tricky problem to get correct. Natural language is difficult for machines to parse.

If you can live with something that will have trouble with honorifics and abbreviations, but be mostly accurate, you could use a fairly simple regex.

use warnings; use strict; my $data; while (my $line = <DATA>){ chomp $line; $data .= " $line"; $data =~ s/ +/ /g; if ($data =~ m/(.+?[\?\.\!]('|")?\s)(?=\p{Upper}|\p{Punct})/){ my $sentence = $1; print $sentence,"\n\n"; substr $data, 0 ,length $sentence, ''; } } print $data if $data; __DATA__ foomatic99 has asked for the wisdom of the Perl Monks concerning the following question: I am looking for a way to chop text at sentence boundaries. I realize that somebody out there must have come up with some heuristics for doing this, though I can't think of any unambiguous terms to search for something like this. I realize that nothing in a reasonably light-weight implementation is going to get it right 100% of the time, but at least I should be able to find something better than just cutting at a certain number of bytes. The text is English, utf8... possibly with HTML entity references. Can anybody help me out here?

There are all kinds of cases where this will fail, but it may be good enough.


In reply to Re: sentence-safe chop heuristics? by thundergnat
in thread sentence-safe chop heuristics? by foomatic99

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.