Determine sentence type: Difference between revisions

Content deleted Content added
→‎{{header|Lua}}: added Lua solution
Rob-codes (talk | contribs)
m Removed extraneous period from sample text. Changed output re this correction.
 
(24 intermediate revisions by 18 users not shown)
Line 24:
{{trans|Go}}
 
<langsyntaxhighlight lang="11l">F sentenceType(s)
I s.empty
R ‘’
Line 43:
 
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))</langsyntaxhighlight>
 
{{out}}
Line 52:
=={{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 89:
)
)
END</langsyntaxhighlight>
{{out}}
<pre>
Line 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 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">
<lang AWK>
# syntax: GAWK -f DETERMINE_SENTENCE_TYPE.AWK
BEGIN {
Line 147:
sentence = ""
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 159:
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}}==
<langsyntaxhighlight 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
Line 214 ⟶ 270:
stream$putc(po, c)
end
end start_up </langsyntaxhighlight>
{{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|Emacs Lisp}}==
<syntaxhighlight lang="lisp">
(defun get-last-character (str)
"Return the last character of STR."
(let ((str-length))
(setq str-length (length str))
(substring str (- str-length 1) str-length)))
 
(defun classify-sentence (str)
"Classify the type of sentence based on final punctuation."
(let ((last-character (get-last-character str)))
(cond ((string= last-character ".") (format "S - %s" str))
((string= last-character "!") (format "E - %s" str))
((string= last-character "?") (format "Q - %s" str))
(t (format "N - %s" str)))))
 
(defun classify-multiple-sentences (str)
"Classify each sentence as Q, S, E, or N."
;; sentence boundary is defined as:
;; a period (full stop), comma, or question mark
;; followed by one space
;; followed by a capital letter
;; while the above will work for this exercise, it won't
;; work in other situations. See the Perl code in this section
;; for cases that the above will not cover.
(let ((regex-sentence-boundary "\\([.?!]\\) \\([[:upper:]]\\)"))
;; split the text into list of individual sentences
(dolist (one-sentence (split-string (replace-regexp-in-string regex-sentence-boundary "\\1\n\\2" str) "\n"))
;; classify each sentence
(insert (format "\n%s" (classify-sentence one-sentence))))))
</syntaxhighlight>
 
To run the Emacs Lisp code, evaluate the following:
 
(classify-multiple-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")
{{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
</pre>
 
 
=={{header|Epoxy}}==
<langsyntaxhighlight lang="epoxy">const SentenceTypes: {
["?"]:"Q",
["."]:"S",
Line 243 ⟶ 415:
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")</langsyntaxhighlight>
{{out}}
<pre>
Line 255 ⟶ 427:
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 312 ⟶ 484:
"Hello, Mr. Anderson!" show
nl
"Are you sure?!?! How can you know?" show</langsyntaxhighlight>
{{out}}
<pre>
Line 330 ⟶ 502:
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight 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
Line 359 ⟶ 531:
while len(spam)>0
print sentype(spam)
wend</langsyntaxhighlight>
{{out}}<pre>Q
S
Line 366 ⟶ 538:
</pre>
 
=={{header|FutureBasic}}==
<syntaxhighlight lang="futurebasic">
local fn SentenceType( sentence as CFStringRef ) as CFStringRef
CFStringRef type
select ( fn StringCharacterAtIndex( sentence, len(sentence)-1 ) )
case _"?" : type = @"Q"
case _"." : type = @"S"
case _"!" : type = @"E"
case else : type = @"N"
end select
end fn = type
 
print fn SentenceType( @"hi there, how are you today?" )
print fn SentenceType( @"I'd like to present to you the washing machine 9001." )
print fn SentenceType( @"You have been nominated to win one of these!" )
print fn SentenceType( @"Just make sure you don't break it" )
 
HandleEvents
</syntaxhighlight>
{{output}}
<pre>
Q
S
E
N
</pre>
 
=={{header|Go}}==
{{trans|Wren}}
<langsyntaxhighlight lang="go">package main
 
import (
Line 399 ⟶ 597:
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>
 
Line 412 ⟶ 652:
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">
<lang jq>
# Input: a string
# Output: a stream of sentence type indicators
Line 433 ⟶ 673:
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</langsyntaxhighlight>
{{out}}
<pre>
Line 443 ⟶ 683:
 
=={{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 455 ⟶ 695:
println(rpad(parsed[i] * parsed[i + 1], 52), " ==> ", haspunctotype(parsed[i + 1]))
end
</langsyntaxhighlight>{{out}}
<pre>
Hi there, how are you today? ==> Q
Line 464 ⟶ 704:
 
=={{header|Lua}}==
<langsyntaxhighlight 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</langsyntaxhighlight>
{{out}}
<pre>hi there, how are you today?: Q
Line 474 ⟶ 714:
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|PascalABC.NET}}==
<syntaxhighlight lang="delphi">
function SentenceType(s: string): char;
begin
case s[^1] of
'?': Result := 'Q';
'!': Result := 'E';
'.': Result := 'S';
else Result := 'N';
end;
end;
 
begin
var ss := Arr('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');
foreach var s in ss do
Println(s,'->',SentenceType(s));
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|Perl}}==
<langsyntaxhighlight lang="perl">use strict;
use warnings;
use feature 'say';
Line 502 ⟶ 812:
else { say 'N' }
}
}</langsyntaxhighlight>
{{out}}
<pre>hi there, how are you today?| Q
Line 512 ⟶ 822:
 
=={{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 522 ⟶ 832:
<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 529 ⟶ 839:
 
=={{header|Python}}==
<langsyntaxhighlight lang="python">import re
 
txt = """
Line 544 ⟶ 854:
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 554 ⟶ 864:
 
Or for more generality, and an alternative to hand-crafted regular expressions:
<langsyntaxhighlight lang="python">'''Grouping and tagging by final character of string'''
 
from functools import reduce
Line 667 ⟶ 977:
# MAIN ---
if __name__ == '__main__':
main()</langsyntaxhighlight>
{{Out}}
<pre>('E', ['You have been nominated to win one of these!', "But perhaps substance isn't the goal!"])
Line 673 ⟶ 983:
('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 689 ⟶ 1,020:
PARAGRAPH
 
say join "\n\n", $paragraph.&get_sentencessentences.map: {
/(<:punct>)$/;
$_ ~ ' | ' ~ do
Line 698 ⟶ 1,029:
default { 'N' };
}
}</langsyntaxhighlight>
{{out}}
<pre>hi there, how are you today? | Q
Line 715 ⟶ 1,046:
 
The syntax highlighting here for Raku isn't the best. | S</pre>
 
=={{header|Refal}}==
<syntaxhighlight lang="refal">$ENTRY Go {
, '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': e.Sentences
= <Prout <SentenceTypes e.Sentences>>;
};
 
SentenceTypes {
e.X '?' = Q;
e.X '? ' e.Y = Q <SentenceTypes e.Y>;
e.X '.' = S;
e.X '. ' e.Y = S <SentenceTypes e.Y>;
e.X '!' = E;
e.X '! ' e.Y = E <SentenceTypes e.Y>;
e.X = N;
}</syntaxhighlight>
{{out}}
<pre>Q S E N</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 734 ⟶ 1,228:
 
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}}
Line 742 ⟶ 1,236:
<br>
{{libheader|Wren-pattern}}
{{libheader|Wren-traititerate}}
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.
<langsyntaxhighlight ecmascriptlang="wren">import "./pattern" for Pattern
import "./traititerate" for Indexed
 
var map = { "?": "Q", "!": "E", ".": "S", "": "N" }
Line 771 ⟶ 1,265:
}
System.print()
}</langsyntaxhighlight>
 
{{out}}
Line 785 ⟶ 1,279:
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}}
<pre>
Q|S|E|N
</pre>