Determine sentence type: Difference between revisions

added Easylang
(added Easylang)
 
(34 intermediate revisions by 23 users not shown)
Line 3:
[[Category:String manipulation]]
 
Use thisthese sentencesentences:
"hi there, how are you today? I'd like to present to you the washing machine 9001. You have been nominated to win one of these! Just make sure you don't break it."
 
;Task
: Search for the last used punctuation in a sentence, and determine its type according to its punctuation.
 
; Output one of these letters: "E" (Exclamation!), "Q" (Question?), "S" (Serious.), "N" (Neutral).
 
;Extra
: Make your code able to determine multiple sentences.
 
 
Line 20:
{{Template:Strings}}
<br><br>
 
=={{header|11l}}==
{{trans|Go}}
 
<syntaxhighlight lang="11l">F sentenceType(s)
I s.empty
R ‘’
 
[Char] types
L(c) s
I c == ‘?’
types.append(Char(‘Q’))
E I c == ‘!’
types.append(Char(‘E’))
E I c == ‘.’
types.append(Char(‘S’))
 
I s.last !C ‘?!.’
types.append(Char(‘N’))
 
R types.join(‘|’)
 
V s = ‘hi there, how are you today? I'd like to present to you the washing machine 9001. You have been nominated to win one of these! Just make sure you don't break it’
print(sentenceType(s))</syntaxhighlight>
 
{{out}}
<pre>
Q|S|E|N
</pre>
 
=={{header|ALGOL 68}}==
Classifies an empty string as "".
<langsyntaxhighlight lang="algol68">BEGIN # determuine the type of a sentence by looking at the final punctuation #
CHAR exclamation = "E"; # classification codes... #
CHAR question = "Q";
Line 60 ⟶ 89:
)
)
END</langsyntaxhighlight>
{{out}}
<pre>
Line 67 ⟶ 96:
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight lang="autohotkey">Sentence := "hi there, how are you today? I'd like to present to you the washing machine 9001. You have been nominated to win one of these! Just make sure you don't break it"
Msgbox, % SentenceType(Sentence)
 
Line 82 ⟶ 111:
}
return (D = SubStr(Sentence, 1, 3)) ? RTrim(RTrim(type, "|"), "N|") : RTrim(type, "|")
}</langsyntaxhighlight>
 
{{out}}
<pre>Q|S|E|N</pre>
=={{header|AWK}}==
<syntaxhighlight lang="awk">
# syntax: GAWK -f DETERMINE_SENTENCE_TYPE.AWK
BEGIN {
str = "hi there, how are you today? I'd like to present to you the washing machine 9001. You have been nominated to win one of these! Just make sure you don't break it"
main(str)
main("Exclamation! Question? Serious. Neutral")
exit(0)
}
function main(str, c) {
while (length(str) > 0) {
c = substr(str,1,1)
sentence = sentence c
if (c == "!") {
prn("E")
}
else if (c == ".") {
prn("S")
}
else if (c == "?") {
prn("Q")
}
str = substr(str,2)
}
prn("N")
print("")
}
function prn(type) {
gsub(/^ +/,"",sentence)
printf("%s %s\n",type,sentence)
sentence = ""
}
</syntaxhighlight>
{{out}}
<pre>
Q hi there, how are you today?
S I'd like to present to you the washing machine 9001.
E You have been nominated to win one of these!
N Just make sure you don't break it
 
E Exclamation!
Q Question?
S Serious.
N Neutral
</pre>
 
=={{header|Bruijn}}==
<syntaxhighlight lang="bruijn">
:import std/List .
:import std/Char .
 
determine [∅?0 '?' ([(0 =? '?' 'Q' (0 =? '.' 'S' (0 =? '!' 'E' 'N')))] _0)]
 
:test (determine empty) ('?')
:test (determine "hi there, how are you today?") ('Q')
:test (determine "I'd like to present to you the washing machine 9001.") ('S')
:test (determine "You have been nominated to win one of these!") ('E')
:test (determine "Just make sure you don't break it") ('N')
</syntaxhighlight>
 
=={{header|C++}}==
<syntaxhighlight lang="c++">
 
#include <exception>
#include <iostream>
#include <string>
#include <vector>
 
char sentence_type(const std::string& sentence) {
if ( sentence.empty() ) {
throw std::invalid_argument("Cannot classify an empty sentence");
}
 
char result;
const char last_character = sentence.back();
switch (last_character) {
case '?': result = 'Q'; break;
case '.': result = 'S'; break;
case '!': result = 'E'; break;
default: result = 'N'; break;
};
return result;
}
 
int main() {
const std::vector<std::string> sentences = { "hi there, how are you today?",
"I'd like to present to you the washing machine 9001.",
"You have been nominated to win one of these!",
"Just make sure you don't break it" };
 
for ( const std::string& sentence : sentences ) {
std::cout << sentence << " -> " << sentence_type(sentence) << std::endl;
}
}
</syntaxhighlight>
<pre>
hi there, how are you today? -> Q
I'd like to present to you the washing machine 9001. -> S
You have been nominated to win one of these! -> E
Just make sure you don't break it -> N
</pre>
 
=={{header|CLU}}==
<syntaxhighlight lang="clu">% This iterator takes a string and yields one of 'E', 'Q',
% 'S' or 'N' for every sentence found.
% Because sentences are separated by punctuation, only the
% last one can be 'N'.
 
sentence_types = iter (s: string) yields (char)
own punct: string := "!?." % relevant character classes
own space: string := " \t\n"
own types: string := "EQS" % sentence type characters
prev_punct: bool := false % whether the previous character was punctuation
last_punct: int := 0 % index of last punctuation character encountered
sentence: bool := true % whether there are words since the last punctuation
for c: char in string$chars(s) do
pu: int := string$indexc(c, punct)
sp: int := string$indexc(c, space)
if pu ~= 0 then
prev_punct := true
last_punct := pu
elseif sp ~= 0 then
if prev_punct then
% a space after punctuation means a sentence has ended here
yield(types[last_punct])
sentence := false
end
prev_punct := false
sentence := false
else
sentence := true
end
end
% handle the last sentence
if prev_punct then yield(types[last_punct])
elseif sentence then yield('N')
end
end sentence_types
 
% Test
start_up = proc ()
po: stream := stream$primary_output()
test: string :=
"hi there, how are you today? I'd like to " ||
"present to you the washing machine 9001. You " ||
"have been nominated to win one of these! Just " ||
"make sure you don't break it"
 
% print the type of each sentence
for c: char in sentence_types(test) do
stream$putc(po, c)
end
end start_up </syntaxhighlight>
{{out}}
<pre>QSEN</pre>
 
 
=={{header|Delphi}}==
{{works with|Delphi|6.0}}
{{libheader|SysUtils,StdCtrls}}
 
 
<syntaxhighlight lang="Delphi">
const TestStrings = 'hi there, how are you today? I''''d like to present to you the washing machine 9001. You have been nominated to win one of these! Just make sure you don''''t break it';
 
procedure AnalyzeSentenceType(Memo: TMemo; S: string);
{Extract sentences from string and analyze terminating punctuation}
var I: integer;
var Sent,SType: string;
begin
Sent:='';
for I:=1 to Length(S) do
begin
Sent:=Sent+S[I];
{Look terminating char or condition}
if (S[I] in ['?','!','.']) or (I>=Length(S)) then
begin
{If found, determine sentence type}
case Sent[Length(Sent)] of
'?': SType:=' (Q)';
'!': SType:=' (E)';
'.': SType:=' (S)';
else SType:=' (N)';
end;
{Display it}
Memo.Lines.Add(Trim(Sent)+SType);
Sent:='';
end;
end;
end;
 
 
procedure TestSentenceTypes(Memo: TMemo);
{Analyze some test sentences}
begin
AnalyzeSentenceType(Memo, TestStrings);
end;
 
</syntaxhighlight>
{{out}}
<pre>
hi there, how are you today? (Q)
I''d like to present to you the washing machine 9001. (S)
You have been nominated to win one of these! (E)
Just make sure you don''t break it (N)
</pre>
 
=={{header|EasyLang}}==
<syntaxhighlight>
func$ stype s$ .
h$ = substr s$ len s$ 1
ind = strpos "?!." h$ mod1 4
return substr "QESN" ind 1
.
txt$[] = [ "hi there, how are you today?" "I'd like to present to you the washing machine 9001." "You have been nominated to win one of these!" "Just make sure you don't break it" ]
for t$ in txt$[]
print t$ & " -> " & stype t$
.
</syntaxhighlight>
{{out}}
<pre>
hi there, how are you today? -> Q
I'd like to present to you the washing machine 9001. -> S
You have been nominated to win one of these! -> E
Just make sure you don't break it -> N
</pre>
 
=={{header|Epoxy}}==
<syntaxhighlight lang="epoxy">const SentenceTypes: {
["?"]:"Q",
["."]:"S",
["!"]:"E"
}
 
fn DetermineSentenceType(Char)
return SentenceTypes[Char]||"N"
cls
 
fn GetSentences(Text)
var Sentences: [],
Index: 0,
Length: #Text
loop i:0;i<Length;i+:1 do
var Char: string.subs(Text,i,1)
var Type: DetermineSentenceType(Char)
if Type != "N" || i==Length-1 then
log(string.sub(Text,Index,i+1)+" ("+Type+")")
Index:i+2;
cls
cls
cls
 
GetSentences("hi there, how are you today? I'd like to present to you the washing machine 9001. You have been nominated to win one of these! Just make sure you don't break it")</syntaxhighlight>
{{out}}
<pre>
hi there, how are you today? (Q)
I'd like to present to you the washing machine 9001. (S)
You have been nominated to win one of these! (E)
Just make sure you don't break it (N)
</pre>
 
=={{header|Factor}}==
This program attempts to prevent common abbreviations from ending sentences early. It also tries to handle parenthesized sentences and implements an additional type for exclamatory questions (EQ).
{{works with|Factor|0.99 2021-06-02}}
<langsyntaxhighlight lang="factor">USING: combinators io kernel regexp sequences sets splitting
wrap.strings ;
 
Line 147 ⟶ 439:
"Hello, Mr. Anderson!" show
nl
"Are you sure?!?! How can you know?" show</langsyntaxhighlight>
{{out}}
<pre>
Line 162 ⟶ 454:
 
Are you sure?!?! How can you know? -> EQ|Q
</pre>
 
=={{header|FreeBASIC}}==
<syntaxhighlight lang="freebasic">function sentype( byref s as string ) as string
'determines the sentence type of the first sentence in the string
'returns "E" for an exclamation, "Q" for a question, "S" for serious
'and "N" for neutral.
'modifies the string to remove the first sentence
for i as uinteger = 1 to len(s)
if mid(s, i, 1) = "!" then
s=right(s,len(s)-i)
return "E"
end if
if mid(s, i, 1) = "." then
s=right(s,len(s)-i)
return "S"
end if
if mid(s, i, 1) = "?" then
s=right(s,len(s)-i)
return "Q"
end if
next i
'if we get to the end without encountering punctuation, this
'must be a neutral sentence, which can only happen as the last one
s=""
return "N"
end function
 
dim as string spam = "hi there, how are you today? I'd like to present to you the washing machine 9001. You have been nominated to win one of these! Just make sure you don't break it"
 
while len(spam)>0
print sentype(spam)
wend</syntaxhighlight>
{{out}}<pre>Q
S
E
N
</pre>
 
=={{header|Go}}==
{{trans|Wren}}
<langsyntaxhighlight lang="go">package main
 
import (
Line 196 ⟶ 525:
s := "hi there, how are you today? I'd like to present to you the washing machine 9001. You have been nominated to win one of these! Just make sure you don't break it"
fmt.Println(sentenceType(s))
}</langsyntaxhighlight>
 
{{out}}
<pre>
Q|S|E|N
</pre>
 
=={{header|Java}}==
<syntaxhighlight lang="java">
 
import java.util.List;
 
public final class DetermineSentenceType {
 
public static void main(String[] aArgs) {
List<String> sentences = List.of( "hi there, how are you today?",
"I'd like to present to you the washing machine 9001.",
"You have been nominated to win one of these!",
"Just make sure you don't break it" );
 
for ( String sentence : sentences ) {
System.out.println(sentence + " -> " + sentenceType(sentence));
}
}
private static char sentenceType(String aSentence) {
if ( aSentence.isEmpty() ) {
throw new IllegalArgumentException("Cannot classify an empty sentence");
}
final char lastCharacter = aSentence.charAt(aSentence.length() - 1);
return switch (lastCharacter) {
case '?' -> 'Q';
case '.' -> 'S';
case '!' -> 'E';
default -> 'N';
};
}
}
</syntaxhighlight>
{{ out }}
<pre>
hi there, how are you today? -> Q
I'd like to present to you the washing machine 9001. -> S
You have been nominated to win one of these! -> E
Just make sure you don't break it -> N
</pre>
 
=={{header|jq}}==
{{works with|jq}}
'''Works with gojq, the Go implementation of jq'''
 
The following parses sentences with embedded quotations naively,
so that for example the sentence "He asked 'How are you?'." results in: Q S
<syntaxhighlight lang="jq">
# Input: a string
# Output: a stream of sentence type indicators
def sentenceTypes:
def trim: sub("^ +";"") | sub(" +$";"");
def parse:
capture("(?<s>[^?!.]*)(?<p>[?!.])(?<remainder>.*)" )
// {p:"", remainder:""};
def encode:
if . == "?" then "Q"
elif . == "!" then "E"
elif . == "." then "S"
else "N"
end;
trim
| select(length>0)
| parse
| (.p | encode), (.remainder | sentenceTypes);
 
def s: "hi there, how are you today? I'd like to present to you the washing machine 9001. You have been nominated to win one of these! Just make sure you don't break it";
 
s | sentenceTypes</syntaxhighlight>
{{out}}
<pre>
Q
S
E
N
</pre>
 
=={{header|Julia}}==
<langsyntaxhighlight lang="julia">const text = """
Hi there, how are you today? I'd like to present to you the washing machine 9001.
You have been nominated to win one of these! Just make sure you don't break it"""
Line 216 ⟶ 623:
println(rpad(parsed[i] * parsed[i + 1], 52), " ==> ", haspunctotype(parsed[i + 1]))
end
</langsyntaxhighlight>{{out}}
<pre>
Hi there, how are you today? ==> Q
Line 223 ⟶ 630:
Just make sure you don't break it ==> N
</pre>
 
=={{header|Lua}}==
<syntaxhighlight lang="lua">text = "hi there, how are you today? I'd like to present to you the washing machine 9001. You have been nominated to win one of these! Just make sure you don't break it"
p2t = { [""]="N", ["."]="S", ["!"]="E", ["?"]="Q" }
for s, p in text:gmatch("%s*([^%!%?%.]+)([%!%?%.]?)") do
print(s..p..": "..p2t[p])
end</syntaxhighlight>
{{out}}
<pre>hi there, how are you today?: Q
I'd like to present to you the washing machine 9001.: S
You have been nominated to win one of these!: E
Just make sure you don't break it: N</pre>
 
=={{header|Nim}}==
<syntaxhighlight lang="Nim">type SentenceType {.pure.} = enum Q, E, S, N
 
func sentenceType(s: string): SentenceType =
## Return the type of a sentence.
if s.len == 0: return
result = case s[^1]
of '?': Q
of '!': E
of '.': S
else: N
 
iterator sentences(text: string): string =
## Cut a text into sentences.
var sentence = ""
for ch in text:
if ch == ' ' and sentence.len == 0: continue
sentence.add ch
if ch in "?!.":
yield sentence
sentence.reset()
if sentence.len > 0:
yield sentence
 
 
const Text = "hi there, how are you today? " &
"I'd like to present to you the washing machine 9001. " &
"You have been nominated to win one of these!" &
"Just make sure you don't break it"
 
for sentence in Text.sentences():
echo sentence, " → ", sentenceType(sentence)
</syntaxhighlight>
 
{{out}}
<pre>hi there, how are you today? → Q
I'd like to present to you the washing machine 9001. → S
You have been nominated to win one of these! → E
Just make sure you don't break it → N
</pre>
 
=={{header|Perl}}==
<syntaxhighlight lang="perl">use strict;
use warnings;
use feature 'say';
use Lingua::Sentence;
 
my $para1 = <<'EOP';
hi there, how are you today? I'd like to present to you the washing machine
9001. You have been nominated to win one of these! Just make sure you don't
break it
EOP
 
my $para2 = <<'EOP';
Just because there are punctuation characters like "?", "!" or especially "."
present, it doesn't necessarily mean you have reached the end of a sentence,
does it Mr. Magoo? The syntax highlighting here for Perl isn't bad at all.
EOP
 
my $splitter = Lingua::Sentence->new("en");
for my $text ($para1, $para2) {
for my $s (split /\n/, $splitter->split( $text =~ s/\n//gr ) {
print "$s| ";
if ($s =~ /!$/) { say 'E' }
elsif ($s =~ /\?$/) { say 'Q' }
elsif ($s =~ /\.$/) { say 'S' }
else { say 'N' }
}
}</syntaxhighlight>
{{out}}
<pre>hi there, how are you today?| Q
I'd like to present to you the washing machine 9001.| S
You have been nominated to win one of these!| E
Just make sure you don't break it.| N
Just because there are punctuation characters like "?", "!" or especially "." present, it doesn't necessarily mean you have reached the end of a sentence, does it Mr. Magoo?| Q
The syntax highlighting here for Perl isn't bad at all.| S</pre>
 
=={{header|Phix}}==
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">constant</span> <span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">`hi there, how are you today? I'd like to present
Line 235 ⟶ 731:
<span style="color: #000000;">w</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">join</span><span style="color: #0000FF;">(</span><span style="color: #000000;">v</span><span style="color: #0000FF;">,</span><span style="color: #008000;">'|'</span><span style="color: #0000FF;">)</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">w</span>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 242 ⟶ 738:
 
=={{header|Python}}==
<langsyntaxhighlight lang="python">import re
 
txt = """
Line 257 ⟶ 753:
for i in range(0, len(pars)-1, 2):
print((pars[i] + pars[i + 1]).ljust(54), "==>", haspunctotype(pars[i + 1]))
</langsyntaxhighlight>{{out}}
<pre>
Hi there, how are you today? ==> Q
Line 266 ⟶ 762:
 
 
Or for more generality, and an alternative to hand-crafted regular expressions:
<syntaxhighlight lang="python">'''Grouping and tagging by final character of string'''
 
from functools import reduce
from itertools import groupby
 
 
# tagGroups :: Dict -> [String] -> [(String, [String])]
def tagGroups(tagDict):
'''A list of (Tag, SentenceList) tuples, derived
from an input text and a supplied dictionary of
tags for each of a set of final punctuation marks.
'''
def go(sentences):
return [
(tagDict.get(k, 'Not punctuated'), list(v))
for (k, v) in groupby(
sorted(sentences, key=last),
key=last
)
]
return go
 
 
# sentenceSegments :: Chars -> String -> [String]
def sentenceSegments(punctuationChars):
'''A list of sentences delimited by the supplied
punctuation characters, where these are followed
by spaces.
'''
def go(s):
return [
''.join(cs).strip() for cs
in splitBy(
sentenceBreak(punctuationChars)
)(s)
]
return go
 
 
# sentenceBreak :: Chars -> (Char, Char) -> Bool
def sentenceBreak(finalPunctuation):
'''True if the first of two characters is a final
punctuation mark and the second is a space.
'''
def go(a, b):
return a in finalPunctuation and " " == b
return go
 
 
# ------------------------- TEST -------------------------
# main :: IO ()
def main():
'''Join, segmentation, tags'''
 
tags = {'!': 'E', '?': 'Q', '.': 'S'}
 
# Joined by spaces,
sample = ' '.join([
"Hi there, how are you today?",
"I'd like to present to you the washing machine 9001.",
"You have been nominated to win one of these!",
"Might it be possible to add some challenge to this task?",
"Feels as light as polystyrene filler.",
"But perhaps substance isn't the goal!",
"Just make sure you don't break off before the"
])
 
# segmented by punctuation,
sentences = sentenceSegments(
tags.keys()
)(sample)
 
# and grouped under tags.
for kv in tagGroups(tags)(sentences):
print(kv)
 
 
# ----------------------- GENERIC ------------------------
 
# last :: [a] -> a
def last(xs):
'''The last element of a non-empty list.'''
return xs[-1]
 
 
# splitBy :: (a -> a -> Bool) -> [a] -> [[a]]
def splitBy(p):
'''A list split wherever two consecutive
items match the binary predicate p.
'''
# step :: ([[a]], [a], a) -> a -> ([[a]], [a], a)
def step(acp, x):
acc, active, prev = acp
 
return (acc + [active], [x], x) if p(prev, x) else (
(acc, active + [x], x)
)
 
# go :: [a] -> [[a]]
def go(xs):
if 2 > len(xs):
return xs
else:
h = xs[0]
ys = reduce(step, xs[1:], ([], [h], h))
# The accumulated sublists, and the final group.
return ys[0] + [ys[1]]
 
return go
 
 
# MAIN ---
if __name__ == '__main__':
main()</syntaxhighlight>
{{Out}}
<pre>('E', ['You have been nominated to win one of these!', "But perhaps substance isn't the goal!"])
('S', ["I'd like to present to you the washing machine 9001.", 'Feels as light as polystyrene filler.'])
('Q', ['Hi there, how are you today?', 'Might it be possible to add some challenge to this task?'])
('Not punctuated', ["Just make sure you don't break off before the"])</pre>
 
=={{header|Racket}}==
<syntaxhighlight lang="racket">
#lang racket
 
(define input "hi there, how are you today? I'd like to present to you the washing machine 9001. You have been nominated to win one of these! Just make sure you don't break it")
 
(define sentence-types #hash((#\. . "S") (#\? . "Q") (#\! . "E")))
(define punctuation (hash-keys sentence-types))
 
(let ([characters (string->list input)])
(for ([i characters])
(when (member i punctuation)
(printf "~a|" (hash-ref sentence-types i))))
(unless (member (last characters) punctuation)
(printf "N")))
</syntaxhighlight>
{{out}}
<pre>
Q|S|E|N
</pre>
 
=={{header|Raku}}==
 
<syntaxhighlight lang="raku" perl6line>use Lingua::EN::Sentence;
 
my $paragraph = q:to/PARAGRAPH/;
Line 282 ⟶ 919:
PARAGRAPH
 
say join "\n\n", $paragraph.&get_sentencessentences.map: {
/(<:punct>)$/;
$_ ~ ' | ' ~ do
Line 291 ⟶ 928:
default { 'N' };
}
}</langsyntaxhighlight>
{{out}}
<pre>hi there, how are you today? | Q
Line 308 ⟶ 945:
 
The syntax highlighting here for Raku isn't the best. | S</pre>
 
=={{header|Ring}}==
<syntaxhighlight lang="ring">
see "working..." + nl
sType = []
sent = "hi there, how are you today? I'd like to present to you the washing machine 9001. You have been nominated to win one of these! How do you like this washing machine? Buy it, don't hesitate! You will be satisfied with it. Just make sure you don't break it"
 
ind = 1
while true
pos = substring(sent,"?",ind)
if pos > 0
add(sType,pos)
ind = pos+1
else
exit
ok
end
 
ind = 1
while true
pos = substring(sent,"!",ind)
if pos > 0
add(sType,pos)
ind = pos+1
else
exit
ok
end
 
ind = 1
while true
pos = substring(sent,".",ind)
if pos > 0
add(sType,pos)
ind = pos+1
else
exit
ok
end
 
if pos < len(sent)
neut = "N"
else
neut = ""
ok
 
sType = sort(sType)
 
text = ""
for n = 1 to len(sType)
if sent[sType[n]] = "?"
text = text + "Q" + "|"
ok
if sent[sType[n]] = "!"
text = text + "E" + "|"
ok
if sent[sType[n]] = "."
text = text + "S" + "|"
ok
next
see text + neut + nl
see "done..." + nl
 
func substring str,substr,n
newstr=right(str,len(str)-n+1)
nr = substr(newstr, substr)
if nr = 0
return 0
else
return n + nr -1
ok
</syntaxhighlight>
{{out}}
<pre>
working...
Q|S|E|Q|E|S|N
done...
</pre>
 
=={{header|RPL}}==
{{works with|Halcyon Calc|4.2.8}}
≪ OVER SIZE → str seps len
≪ 1 CF { 0 } 1 len FOR j
IF seps str j DUP SUB POS THEN
j + IF j len == THEN 1 SF END
END NEXT
IF 1 FC? THEN len + END
{ } SWAP 1 OVER SIZE 1 - FOR j
str OVER j GETI 1 + ROT ROT
GET SUB ROT SWAP + SWAP
NEXT DROP
≫ ≫ ''''PARSE'''' STO
≪ "?!." SWAP OVER '''PARSE''' "QES" → seps sents types
≪ 1 sents SIZE FOR j
sents j GET seps
IF OVER DUP SIZE DUP SUB POS THEN
"=" types LAST DUP SUB +
ELSE "=N" END +
NEXT
≫ ≫ ''''STYPE'''' STO
 
"hi there, how are you today? I'd like to present to you the washing machine 9001. You have been nominated to win one of these! Just make sure you don't break it" '''STYPE'''
{{out}}
<pre>
4: "hi there, how are you today?=Q"
3: " I'd like to present to you the washing machine 9001.=S"
2: " You have been nominated to win one of these!=E"
1: " Just make sure you don't break it=N"
</pre>
 
=={{header|V (Vlang)}}==
{{trans|Go}}
<syntaxhighlight lang="v (vlang)">fn sentence_type(s string) string {
if s.len == 0 {
return ""
}
mut types := []string{}
for c in s.split('') {
if c == '?' {
types << "Q"
} else if c == '!' {
types << "E"
} else if c == '.' {
types << "S"
}
}
if s[s.len-1..s.len].index_any('?!.') == -1 {
types << "N"
}
return types.join("|")
}
fn main() {
s := "hi there, how are you today? I'd like to present to you the washing machine 9001. You have been nominated to win one of these! Just make sure you don't break it"
println(sentence_type(s))
}</syntaxhighlight>
 
{{out}}
<pre>
Q|S|E|N
</pre>
 
=={{header|Wren}}==
<langsyntaxhighlight ecmascriptlang="wren">var sentenceType = Fn.new { |s|
if (s.count == 0) return ""
var types = []
Line 327 ⟶ 1,106:
 
var s = "hi there, how are you today? I'd like to present to you the washing machine 9001. You have been nominated to win one of these! Just make sure you don't break it"
System.print(sentenceType.call(s))</langsyntaxhighlight>
 
{{out}}
<pre>
Q|S|E|N
</pre>
<br>
{{libheader|Wren-pattern}}
{{libheader|Wren-iterate}}
The following alternative version takes the simplistic view that (unless they end the final sentence of the paragraph) '''?''', '''!''' or '''.''' will only end a sentence if they're immediately followed by a space. This of course is nonsense, given the way English is written nowadays, but it's probably an improvement on the first version without the need to search through an inevitably incomplete list of abbreviations.
<syntaxhighlight lang="wren">import "./pattern" for Pattern
import "./iterate" for Indexed
 
var map = { "?": "Q", "!": "E", ".": "S", "": "N" }
var p = Pattern.new("[? |! |. ]")
var paras = [
"hi there, how are you today? I'd like to present to you the washing machine 9001. You have been nominated to win one of these! Just make sure you don't break it",
"hi there, how are you on St.David's day (isn't it a holiday yet?), Mr.Smith? I'd like to present to you (well someone has to win one!) the washing machine 900.1. You have been nominated by Capt.Johnson('?') to win one of these! Just make sure you (or Mrs.Smith) don't break it. By the way, what the heck is an exclamatory question!?"
]
 
for (para in paras) {
para = para.trim()
var sentences = p.splitAll(para)
var endings = p.findAll(para).map { |m| m.text[0] }.toList
var lastChar = sentences[-1][-1]
if ("?!.".contains(lastChar)) {
endings.add(lastChar)
sentences[-1] = sentences[-1][0...-1]
} else {
endings.add("")
}
for (se in Indexed.new(sentences)) {
var ix = se.index
var sentence = se.value
System.print("%(map[endings[ix]]) <- %(sentence + endings[ix])")
}
System.print()
}</syntaxhighlight>
 
{{out}}
<pre>
Q <- hi there, how are you today?
S <- I'd like to present to you the washing machine 9001.
E <- You have been nominated to win one of these!
N <- Just make sure you don't break it
 
Q <- hi there, how are you on St.David's day (isn't it a holiday yet?), Mr.Smith?
S <- I'd like to present to you (well someone has to win one!) the washing machine 900.1.
E <- You have been nominated by Capt.Johnson('?') to win one of these!
S <- Just make sure you (or Mrs.Smith) don't break it.
Q <- By the way, what the heck is an exclamatory question!?
</pre>
 
=={{header|XPL0}}==
<syntaxhighlight lang="xpl0">include xpllib; \for StrLen
int Sentence, N, Len;
char Str;
[Sentence:= ["hi there, how are you today?",
"I'd like to present to you the washing machine 9001.",
"You have been nominated to win one of these!",
"Just make sure you don't break it"];
for N:= 0 to 3 do
[Str:= Sentence(N);
Len:= StrLen(Str);
case Str(Len-1) of
^!: ChOut(0, ^E);
^?: ChOut(0, ^Q);
^.: ChOut(0, ^S)
other ChOut(0, ^N);
if N < 3 then ChOut(0, ^|);
];
]</syntaxhighlight>
 
{{out}}
1,982

edits