3 ms·
TXR Lisp: (defun wordlist-sentence (sentence) [(opip `@1.` (split-str @1 #/\s+/) (cons :start) (remqual "")) sentence])
by kazinator 11y ago
TXR Lisp:
(defun wordlist-sentence (sentence)
[(opip
`@1.`
(split-str @1 #/\s+/)
(cons :start)
(remqual ""))
sentence])
(defun make-markov-mapping (sentence)
(let ((wordlist (wordlist-sentence sentence)))
(hash-from-pairs (mapcar (ret ^(,@1 (,@2))) wordlist (rest wordlist))
:equal-based)))
(defun markov-data (text)
[(opip
(split-str @1 #/\./)
(mapcar make-markov-mapping)
(reduce-left (op hash-uni @1 @2 append) @1 (hash :equal-based)))
text])
(defun pick-next-word (map word)
(let ((choices [map word]))
[choices (rand (length choices))]))
(defun sentence (map)
(for
((words ())
(this-word :start)
(next-word "X"))
((not (eql [next-word -1] #\.))
(cat-str words " "))
((set next-word (pick-next-word map this-word))
(set words ^(,*words ,next-word))
(set this-word next-word))))
Run:
$ txr -i markov.tl
1> (defvar map (markov-data
"Influence in society, however, is a capital which has to be economized \
\ if it is to last. Prince Vasili knew this, and having once realized that \
\ if he asked on behalf of all who begged of him, he would soon be unable \
\ to ask for himself, he became chary of using his influence. But in \
\ Princess Drubetskaya's case he felt, after her second appeal, something \
\ like qualms of conscience. She had reminded him of what was quite true; \
\ he had been indebted to her father for the first steps in his career. \
\ Moreover, he could see by her manners that she was one of those women-- \
\ mostly mothers--who, having once made up their minds, will not rest \
\ until they have gained their end, and are prepared if necessary to go on \
\ insisting day after day and hour after hour, and even to make scenes. \
\ This last consideration moved him."))
map
2> (sentence map)
"Prince Vasili knew this, and having once realized that she was quite true; he
could see by her manners that if it is to ask for himself, he felt, after hour,
and even to last."
- kazinator 11y agosentence function based on giterate instead of for loop. (defun sentence (map) (let* ((words (cdr [giterate true (op pick-next-word map) :start])) (dot (pos-if (op eq [@1 -1] #\.) words))) (cat-str [words 0..(succ dot)] " "))) Requires small weak to pick-next-word (defun pick-next-word (map word) (let ((choices [map word])) (if choices [choices (rand (length choices))]))) giterate returns an infinite list, but we take from it up to the word which ends with dot, ignoring the endless stream of nil objects which follows. Alternative: partition the list on the ending word, then glue the first two partitions: (defun sentence (map) (let* ((words (cdr [giterate true (op pick-next-word map) :start])) (part (partition-by (op eq [@1 -1] #\.) words))) (cat-str (append (first part) (second part)) " ")))