Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add min_words optional argument to make_sentence #128

Merged
merged 2 commits into from
Jun 17, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 4 additions & 3 deletions markovify/text.py
Original file line number Diff line number Diff line change
Expand Up @@ -190,14 +190,15 @@ def make_sentence(self, init_state=None, **kwargs):
If `test_output` is set as False then the `test_sentence_output` check
will be skipped.

If `max_words` is specified, the word count for the sentence will be
evaluated against the provided limit.
If `max_words` or `min_words` are specified, the word count for the sentence will be
evaluated against the provided limit(s).
"""
tries = kwargs.get('tries', DEFAULT_TRIES)
mor = kwargs.get('max_overlap_ratio', DEFAULT_MAX_OVERLAP_RATIO)
mot = kwargs.get('max_overlap_total', DEFAULT_MAX_OVERLAP_TOTAL)
test_output = kwargs.get('test_output', True)
max_words = kwargs.get('max_words', None)
min_words = kwargs.get('min_words', None)

if init_state != None:
prefix = list(init_state)
Expand All @@ -211,7 +212,7 @@ def make_sentence(self, init_state=None, **kwargs):

for _ in range(tries):
words = prefix + self.chain.walk(init_state)
if max_words != None and len(words) > max_words:
if max_words != None and len(words) > max_words or len(words) < min_words:
continue
if test_output and hasattr(self, "rejoined_text"):
if self.test_sentence_output(words, mor, mot):
Expand Down
5 changes: 5 additions & 0 deletions test/test_basic.py
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,11 @@ def test_max_words(self):
sent = text_model.make_sentence(max_words=0)
assert sent is None

def test_min_words(self):
text_model = self.sherlock_model
sent = text_model.make_sentence(min_words=5)
assert len(sent.split(' ')) >= 5

def test_newline_text(self):
with open(os.path.join(os.path.dirname(__file__), "texts/senate-bills.txt")) as f:
model = markovify.NewlineText(f.read())
Expand Down